To solve this problem, we need to read numerical data from a file, compute basic statistical measures (average, maximum, minimum, and count of elements), and write these results to another file.
Approach
- Read Data: Open and read the content of the file
data.txt. Convert the read content into a list of floating-point numbers. - Compute Statistics:
- Average: Sum of all numbers divided by the count of numbers.
- Maximum: The largest number in the list.
- Minimum: The smallest number in the list.
- Count: The number of elements in the list.
- Write Results: Open the file
results.txtand write the computed statistics in a readable format.
Solution Code
# Read data from 'data.txt'
try:
with open('data.txt', 'r') as data_file:
content = data_file.read().strip()
if not content:
raise ValueError("The file 'data.txt' is empty.")
numbers = list(map(float, content.split()))
except FileNotFoundError:
print("Error: 'data.txt' not found.")
exit(1)
except ValueError as e:
print(f"Error: {e}")
exit(1)
# Calculate statistics
average = sum(numbers) / len(numbers)
max_value = max(numbers)
min_value = min(numbers)
count = len(numbers)
# Write results to 'results.txt'
with open('results.txt', 'w') as result_file:
result_file.write(f"Average: {average:.2f}\n")
result_file.write(f"Maximum: {max_value}\n")
result_file.write(f"Minimum: {min_value}\n")
result_file.write(f"Count: {count}\n")
print("Results have been written to 'results.txt'.")
Explanation
- Reading Data: The code reads the content of
data.txtand splits it into individual strings (using whitespace as the delimiter). These strings are then converted to floating-point numbers to handle both integer and decimal values. - Handling Errors: The code checks for common errors like missing files or empty data to ensure robustness.
- Computing Statistics: Basic Python functions (
sum,max,min,len) are used to compute the required statistics. - Writing Results: The results are formatted to two decimal places for the average (for readability) and written to
results.txtin a clear, line-by-line format.
This approach efficiently processes the data and provides the required output in a structured manner. The code is concise, easy to understand, and handles common edge cases.


作者声明:本文包含人工智能生成内容。