采用python文件相关函数和方法,随机生成50个学生的姓名,平时成绩,期中成绩,期末成绩,成绩介于40到100之间,然后输入到成绩表.csv文件中,读取成绩表.csv文件数据计算每个学生最终成绩,最终成绩=平时成绩0.2+期中成绩0.3+期末成绩*0.5,然后将学生姓名和最终成绩写入score.csv文件中,格式要求姓名和最终成绩用逗号隔开,每个学生数据输出后换行
时间: 2023-05-31 12:03:05 浏览: 133
生成学生信息并写入成绩表.csv文件中:
```python
import random
import csv
# 生成50个学生的姓名和成绩
students = []
for i in range(50):
name = f"学生{i+1}"
score1 = random.randint(40, 100)
score2 = random.randint(40, 100)
score3 = random.randint(40, 100)
students.append((name, score1, score2, score3))
# 将学生信息写入csv文件
with open("成绩表.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerow(["姓名", "平时成绩", "期中成绩", "期末成绩"])
writer.writerows(students)
```
读取成绩表.csv文件数据计算每个学生最终成绩,并将学生姓名和最终成绩写入score.csv文件中:
```python
with open("成绩表.csv", "r") as f1, open("score.csv", "w", newline="") as f2:
reader = csv.reader(f1)
writer = csv.writer(f2)
next(reader) # 跳过表头
writer.writerow(["姓名", "最终成绩"])
for row in reader:
name = row[0]
score1 = int(row[1])
score2 = int(row[2])
score3 = int(row[3])
final_score = score1 * 0.2 + score2 * 0.3 + score3 * 0.5
writer.writerow([name, final_score])
print(f"{name}: {final_score:.2f}")
```
阅读全文