将下表数据写入一个文件,然后读取该文件数据,并输出到屏幕,且求取平均值,将每条平均值信息输出到average.txt中。 姓名,数学,语文,英语 张三,78,86,89 曾平,82,98,75 李梅,88,98,82
时间: 2023-08-16 09:06:26 浏览: 164
写入数据到文件:
```python
data = "姓名,数学,语文,英语\n张三,78,86,89\n曾平,82,98,75\n李梅,88,98,82"
with open("scores.txt", "w") as f:
f.write(data)
```
读取文件数据并输出到屏幕:
```python
with open("scores.txt", "r") as f:
lines = f.readlines()
for line in lines:
print(line.strip())
```
求取平均值并将每条平均值信息输出到average.txt中:
```python
with open("scores.txt", "r") as f:
lines = f.readlines()
with open("average.txt", "w") as f2:
f2.write("姓名,平均值\n")
for line in lines[1:]:
name, math, chinese, english = line.strip().split(",")
average = (int(math) + int(chinese) + int(english)) / 3
f2.write(f"{name},{average:.2f}\n")
print(f"{name}的平均值为:{average:.2f}")
```
完整代码:
```python
data = "姓名,数学,语文,英语\n张三,78,86,89\n曾平,82,98,75\n李梅,88,98,82"
with open("scores.txt", "w") as f:
f.write(data)
with open("scores.txt", "r") as f:
lines = f.readlines()
with open("average.txt", "w") as f2:
f2.write("姓名,平均值\n")
for line in lines[1:]:
name, math, chinese, english = line.strip().split(",")
average = (int(math) + int(chinese) + int(english)) / 3
f2.write(f"{name},{average:.2f}\n")
print(f"{name}的平均值为:{average:.2f}")
with open("scores.txt", "r") as f:
lines = f.readlines()
for line in lines:
print(line.strip())
```
阅读全文