Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.write not working in Python

Tags:

python

file

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?

like image 314
Danny Avatar asked May 12 '11 01:05

Danny


People also ask

How does .write work in Python?

The write() method writes a specified text to the file. Where the specified text will be inserted depends on the file mode and stream position. "a" : The text will be inserted at the current file stream position, default at the end of the file.

How to write in a new file Python?

To create and write to a new file, use open with “w” option. The “w” option will delete any previous existing file and create a new file to write. If you want to append to an existing file, then use open statement with “a” option. In append mode, Python will create the file if it does not exist.

Can I write to a file in Python?

Python provides inbuilt functions for creating, writing and reading files. There are two types of files that can be handled in python, normal text files and binary files (written in binary language, 0s and 1s).


2 Answers

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

like image 198
hugomg Avatar answered Sep 28 '22 11:09

hugomg


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) 
like image 44
zeekay Avatar answered Sep 28 '22 13:09

zeekay