采用python文件相关函数和方法,随机生成50个学生的姓名,平时成绩,期中成绩,期末成绩,成绩介于40到100之间,然后输入到成绩表.csv文件中,读取成绩表.csv文件数据计算每个学生最终成绩,最终成绩=平时成绩*0.2+期中成绩*0.3+期末成绩*0.5,然后将学生姓名和最终成绩写入score.csv文件中,格式要求姓名和最终成绩用逗号隔开,每个学生数据输出后换行
时间: 2023-05-30 11:06:23 浏览: 97
# 导入相关模块
import csv
import random
# 随机生成50个学生的姓名和成绩
students = []
for i in range(1, 51):
name = '学生' + str(i)
normal_score = random.randint(40, 100)
midterm_score = random.randint(40, 100)
final_score = random.randint(40, 100)
students.append((name, normal_score, midterm_score, final_score))
# 将数据写入成绩表.csv文件中
with open('成绩表.csv', 'w', newline='') as f:
writer = csv.writer(f)
writer.writerow(['姓名', '平时成绩', '期中成绩', '期末成绩'])
for student in students:
writer.writerow(student)
# 计算每个学生最终成绩,写入score.csv文件中
with open('成绩表.csv', 'r') as f1, open('score.csv', 'w', newline='') as f2:
reader = csv.reader(f1)
writer = csv.writer(f2)
writer.writerow(['姓名', '最终成绩'])
next(reader)
for row in reader:
name = row[0]
normal_score = int(row[1])
midterm_score = int(row[2])
final_score = int(row[3])
total_score = normal_score * 0.2 + midterm_score * 0.3 + final_score * 0.5
writer.writerow([name, total_score])
print(name + ',' + str(total_score))
阅读全文