.write not working in Python
I'm fairly new to Python so hopefully I'm just missing something obvious here, but it has me stumped. Snippet of my program below:
outFile = open('P4Output.txt', 'w')
outFile.write(output)
print output
print "Output saved to \"P4Output.txt\"\n"
output prints correctly to the console, but if I go open up the file it's blank. If I delete the file and execute my program again, the file is created but still is empty. I used this exact same block of code in another program of mine previously and it worked, and still works. However, if I open up Python and try something simple like:
f = open('test.txt', 'w')
f.write("test")
Again, test.txt is created but is left blank. What gives?
Solution 1:
Did you do f.close()
at the end of your program?
Solution 2:
Due to buffering, the string may not actually show up in the file until you call flush()
or close()
. So try to call f.close()
after f.write()
. Also using with
with file objects is recommended, it will automatically close the file for you even if you break out of the with
block early due to an exception or return
statement.
with open('P4Output.txt', 'w') as f:
f.write(output)
Solution 3:
You need to do a
outFile.flush()
if you want the buffered contents to be written to the disk.
If you're done writing to the file, a file.close
call will implicitly flush the buffered data before closing the file.
Solution 4:
Try to enclose your statements in a try / catch block to know if something happens during opening or writing to the file:
try:
outFile = open('P4Output.txt','w')
outFile.write(output)
outFile.close()
except IOError as (errno,strerror):
print "I/O error({0}): {1}".format(errno, strerror)
And always close your file so the system can flush your data to the file before closing it.