My task is to open up a file the user inputs and then output the grade for the student and the average scores for midterm1, midterm2, and final scores. But every time I try to write the string into the output file, the file only takes in the last line of the list. At the same time, the '\n' character does not help. I am a little confused. Any help is greatly appreciated. Here's my code:
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))
CodePudding user response:
You don't need all those inner loops, which don't actually iterate.
You need to move the output.write()
call into the loop, so you write each line after you determine it. Use '\t'.join()
to make the output file a TSV.
Instead of the variables sum
, sum2
, sum3
, you can use a list for all the sums. Then you can use a loop to add to them for each student.
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]