为什么输出只产生write()调用的最后一行



我的任务是打开一个文件,由用户输入,然后输出学生的成绩和平均成绩:

  • 中期1
  • 中期2
  • 期末考试

但每次我试图将字符串写入输出文件时,该文件只会占用列表的最后一行。同时,'n'字符也没有帮助。我有点困惑。

这是我的代码:

sum = 0
sum3 = 0
sum2 = 0
n = []
# TODO: Read a file name from the user and read the tsv file here.
file = input()
with open(file) as f:
data = f.readlines()
# TODO: Compute student grades and exam averages, then output results to a text file here.
with open('report.txt', 'w') as output:
for line in data:
split_line = line.split('t')
sum1 = int(split_line[2]) + int(split_line[3]) + int(split_line[4])
avg = sum1 / 3
# TODO: Compute student grades and exam averages, then output results to a text
# file here.
for i in data:
if avg >= 90:
split_line.append('A'+'n')
if 80 <= avg < 90:
split_line.append('B'+'n')
if 70 <= avg < 80:
split_line.append('C'+'n')
if  60 <= avg < 70:
split_line.append('D'+'n')
if avg < 60:
split_line.append('F'+'n')
break
for j in data:
sum += int(split_line[2])
avg = sum/len(data)
break
for k in data:
sum3 += int(split_line[3])
avg1 = sum3/len(data)
break
for l in data:
sum2 += int(split_line[4])
avg2 = sum2/len(data)
break
for i in data:
output.write(str(split_line))

您不需要所有这些内部循环,它们实际上并不迭代。

您需要将output.write()调用移动到循环中,因此在确定每一行之后编写它。使用't'.join()使输出文件成为TSV。

您可以使用所有和的列表来代替变量sumsum2sum3。然后你可以使用一个循环为每个学生添加。

subject_totals = [0, 0, 0]
with open('report.txt', 'w') as output:
for line in data:
split_line = line.strip().split('t')
grades = [int(i) for i in split_line[2:]]
for i, grade in enumerate(grades):
subject_totals[i] += grade
avg = sum(grades) / len(grades)
if avg >= 90:
split_line.append('A')
elif avg >= 80:
split_line.append('B')
elif avg >= 70:
split_line.append('C')
elif avg >= 60:
split_line.append('D')
else:
split_line.append('F')
output.write('t'.join(split_line) + 'n')

subject_avgs = [total/len(data) for total in subject_totals]

最新更新