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?

0

5 Answers 5

84

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

Sign up to request clarification or add additional context in comments.

2 Comments

do files not .close() themselves when the interpreter exits?
Files are closed when Python exists, but file output is usually buffered and if there is no newline, pending output will not be flushed to the file system.
55

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) 

Comments

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.

Comments

5

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.

Comments

-9

maybe you should use absolute path instead of relative one.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.