将一组学生的信息(姓名、语文成绩、数学成绩、英语成绩)写入到文件score.txt中,一行存储一个学生的信息,各字段间以逗号分隔。然后读取文件中内容计算每个学生的平均分,将结果(姓名,平均成绩)写入到文件result.txt中。
时间: 2023-11-22 17:53:01 浏览: 35
以下是Python代码实现:
写入文件score.txt:
```python
# 学生信息
students = [
{"name": "小明", "chinese": 80, "math": 75, "english": 85},
{"name": "小红", "chinese": 90, "math": 95, "english": 80},
{"name": "小刚", "chinese": 85, "math": 80, "english": 90},
{"name": "小李", "chinese": 75, "math": 90, "english": 95},
]
# 写入文件
with open("score.txt", "w") as f:
for student in students:
f.write("{},{},{},{}\n".format(student["name"], student["chinese"], student["math"], student["english"]))
```
读取文件score.txt并计算平均分,然后写入文件result.txt:
```python
# 读取文件并计算平均分
with open("score.txt", "r") as f:
lines = f.readlines()
results = []
for line in lines:
# 解析学生信息
name, chinese, math, english = line.strip().split(",")
# 计算平均分
average = (int(chinese) + int(math) + int(english)) / 3
# 添加到结果列表
results.append((name, average))
# 写入文件
with open("result.txt", "w") as f:
for result in results:
f.write("{},{}\n".format(result[0], result[1]))
```
这样就完成了将学生信息写入文件,并计算平均分写入新文件的操作。