Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python write function is not writing last entry

Tags:

python

csv

Here is a simplified version of my code. I am trying to write to a file using:

fileName = "missing.csv"
for x in range (0,5):
    print(x)
    saveData = open(fileName, "a")
    saveData.write(str(x)+'\n')
    saveData.close

The console prints:

0, 1, 2, 3, 4

... as it should. However, when I open missing.csv it only contains:

0
1
2
3

NO last entry (the 4).

Any Ideas? Please advise.

like image 595
scminne Avatar asked Dec 19 '25 00:12

scminne


2 Answers

If you use context manager you do not need to worry about close:

fileName = "missing.csv"
for x in range(0, 5):
    print(x)
    with open(fileName, "a") as save_data:
        save_data.write(str(x) + '\n')

And if you do not want to close the file after every operation, you can open and close it only once like:

fileName = "missing.csv"
with open(fileName, "a") as save_data:
    for x in range(0, 5):
        print(x)
        save_data.write(str(x) + '\n')
like image 97
Stephen Rauch Avatar answered Dec 20 '25 18:12

Stephen Rauch


To avoid the error you made in your code (missing the () to .close), you could use a context manager:

fileName = "missing.csv"
for x in range (0,5):
    print(x)
    with open(fileName, "a") as saveData:
        saveData.write(str(x)+'\n')

There's an implicit call to .close() at the exit of the with.. block.

like image 32
pjz Avatar answered Dec 20 '25 17:12

pjz