读取score.txt中的数据(假设文件中存储若干成绩,每行一个成绩),统计分析成绩的个数、最高分、最低分以及平均分,并把结果写入result.txt文件中。设计一个python程序
时间: 2024-11-09 08:21:29 浏览: 33
读取student.txt文件内容,每行作为一条数据,创建对应Student对象。
好的,下面是一个简单的Python脚本,它将完成你所描述的任务:
```python
# 导入必要的模块
import os
def read_scores(filename):
try:
with open(filename, 'r') as file:
scores = [float(line) for line in file] # 从文件中读取并转换为浮点数列表
except FileNotFoundError:
print(f"{filename} not found.")
return None
except ValueError:
print("Error: File contains non-numeric values.")
return None
# 统计信息
num_scores = len(scores)
max_score = max(scores)
min_score = min(scores)
average_score = sum(scores) / num_scores if num_scores > 0 else "No scores"
return num_scores, max_score, min_score, average_score
def write_results(num_scores, stats, result_filename):
content = f"Number of scores: {num_scores}\nMax score: {stats[1]}\nMin score: {stats[2]}\nAverage score: {stats[3]}"
try:
with open(result_filename, 'w') as file:
file.write(content)
print(f"Results written to {result_filename}.")
except Exception as e:
print(f"An error occurred while writing results: {e}")
# 调用函数并处理结果
filename = "score.txt"
result_filename = "result.txt"
scores_stats = read_scores(filename)
if scores_stats is not None:
num_scores, max_score, min_score, avg_score = scores_stats
write_results(num_scores, (max_score, min_score, avg_score), result_filename)
```
在这个程序中,首先尝试打开并读取`score.txt`文件中的数值。然后计算分数的数量、最大值、最小值和平均值(如果有效)。最后,将结果写入`result.txt`文件。
注意:
1. 这个脚本假定文件中的所有内容都是可以转换为浮点数的数字。
2. 如果文件不存在或包含非数字值,程序会给出相应的错误提示。
阅读全文