![](/img/trans.png)
[英]why does my python script write only last line from SELECT sql query
[英]Why does the output only produce the last line of the write() call?
我的任務是打開一個用戶輸入的文件,然后打開 output 學生的成績和平均分數:
但是每次我嘗試將字符串寫入 output 文件時,該文件只接受列表的最后一行。 同時, '\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()
使 output 文件成為 TSV。
除了變量sum
、 sum2
、 sum3
,您可以使用一個列表來表示所有總和。 然后,您可以使用循環為每個學生添加它們。
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]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.