Writing to a text file, last entry is missing

Question:

This code calls no errors, but my text file is not getting betty and her grade. It’s only getting the first three out of the four combinations. What am I doing wrong? Thanks!

students = ['fred','wilma','barney','betty']
grades = [100,75,80,90]
for i in range(4):
    file = open("grades3.txt", "a")
    entry = students[i] + "-" + str(grades[i]) + 'n'
    file.write(entry)
file.close
Asked By: gerald

||

Answers:

It seems that you are opening the file each iteration of the loop, as well as not calling the file.close function. You should have something like this:

students = ['fred','wilma','barney','betty']
grades = [100,75,80,90]
file = open("grades3.txt", "a")
for i in range(4):
    entry = students[i] + "-" + str(grades[i]) + 'n'
    file.write(entry)
file.close()
Answered By: EpicPuppy613

You should use use with open() as ... to automatically open, close and assign the file handle to a variable:

students = ['fred','wilma','barney','betty']
grades = [100,75,80,90]
with open("grades3.txt", "a") as file:
    for i in range(4):
        entry = students[i] + "-" + str(grades[i]) + 'n'
        file.write(entry)
Answered By: B Remmelzwaal

It would be better if you use an approach like this instead of using range():

students = ['fred','wilma','barney','betty']
grades = [100,75,80,90]
with open("grades3.txt","a") as f:
    for student, grade in zip(students,grades):
        f.write(f"{student}-{grade}n")
Answered By: Pedro Rocha
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.