Search code examples
pythonfiletext

Writing to a text file, last entry is missing


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

Solution

  • 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)