.write not working in Python

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.


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)

Did you do f.close() at the end of your program?


Try to enclose your statements in a try/except 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.

Tags:

Python

File