Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading