Alex Rivera | Logout

.write not working in Python

Asked 2011-05-12T01:04:18.107
49

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?

Edit
Report

1 Answer

27

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.

answered 2011-05-12T10:22:06.520

Your Answer