Danny
Danny

Reputation: 3665

.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?

Upvotes: 49

Views: 132143

Answers (5)

hugomg
hugomg

Reputation: 69924

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

Upvotes: 84

Sebastien
Sebastien

Reputation: 264

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.

Upvotes: 5

Andy Ding
Andy Ding

Reputation: 1

maybe you should use absolute path instead of relative one.

Upvotes: -9

Zach Kelling
Zach Kelling

Reputation: 53819

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)

Upvotes: 55

tzot
tzot

Reputation: 95901

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.

Upvotes: 27

Related Questions