I\'m running a test, and found that the file doesn\'t actually get written until I control-C to abort the program. Can anyone explain why that would happen?
I expec
You will want to check out file.flush() - although take note that this might not write the data to disk, to quote:
Note: flush() does not necessarily write the file’s data to disk. Use flush() followed by os.fsync() to ensure this behavior.
Closing the file (file.close()) will also ensure that the data is written - using with
will do this implicitly, and is generally a better choice for more readability and clarity - not to mention solving other potential problems.
You need to f.close()
to flush the file write buffer out to the file. Or in your case you might just want to do a f.flush(); os.fsync();
so you can keep looping with the opened file handle.
Don't forget to import os
.
File Handler to be flushed.
f.flush()
The file does not get written, as the output buffer is not getting flushed until the garbage collection takes effect, and flushes the I/O buffer (more than likely by calling f.close()
).
Alternately, in your loop, you can call f.flush()
followed by os.fsync()
, as documented here.
f.flush()
os.fsync()
All that being said, if you ever plan on sharing the data in that file with other portions of your code, I would highly recommend using a StringIO object.
This is a windows-ism. If you add an explicit .close()
when you're done with file, it'll appear in explorer at that time. Even just flushing it might be enough (I don't have a windows box handy to test). But basically f.write does not actually write, it just appends to the write buffer - until the buffer gets flushed you won't see it.
On unix the files will typically show up as a 0-byte file in this situation.
You have to force the write, so I i use the following lines to make sure a file is written:
# Two commands together force the OS to store the file buffer to disc
f.flush()
os.fsync(f.fileno())