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?
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.
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.
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).
Did you do f.close()
at the end of your program?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With