David542 David542 - 5 months ago 10
Python Question

Python question about write() and truncate()

I am in Terminal on mac and I am learning how to open, close, read, delete files.

When I set

f = open("sample.txt", 'w')

and then hit
the contents delete.

However, when I do
it does not update in the text file. It only updates after I do

I was wondering why this happens (I thought
was supposed to delete the text!)? Why doesn't the text editor update automatically when I type in


f.write() writes into the Python process's own buffer (similarly to the C fwrite() functions). However, the data is not actually flushed into the OS buffers until you call f.flush() or f.close(), or when the buffer fills up. Once you do that, the data becomes visible to all other applications.

Note that the OS does another layer of buffering/caching -- that is shared by all running applications. When the file is flushed, it's written to these buffers, but is not yet written to the disk until some time has passed, or when you call fsync(). If your OS crashes or computer loses power, such unsaved changes will be lost.