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.
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')
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With