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 f.truncate()
the contents delete开发者_开发百科.
However, when I do f.write()
it does not update in the text file. It only updates after I do f.truncate()
.
I was wondering why this happens (I thought f.truncate()
was supposed to delete the text!)? Why doesn't the text editor update automatically when I type in f.write()
?
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.
Lets see an example:
import os
# Required for fsync method: see below
f = open("sample.txt", 'w+')
# Opens sample.txt for reading/writing
# File pointer is at position 0
f.write("Hello")
# String "Hello" is written into sample.txt
# Now the file pointer is at position 5
f.read()
# Prints nothing because file pointer is at position 5 & there
# is no data after that
f.seek (0)
# Now the file pointer is at position 0
f.read()
# Prints "Hello" on Screen
# Now the file pointer is again at position 5
f.truncate()
# Nothing will happen, because the file pointer is at position 5
# & the truncate method truncate the file from position 5.
f.seek(0)
# Now the file pointer at position 0
f.truncate()
# Trucate method Trucates everything from position 0
# File pointer is at position 0
f.write("World")
# This will write String "World" at position 0
# File pointer is now at position 5
f.flush()
# This will empty the IOBuffer
# Flush method may or may not work depends on your OS
os.fsync(f)
# fsync method from os module ensures that all internal buffers
# associated with file are written to the disk
f.close()
# Flush & close the file object f
For performance reasons, output to files is buffered. Therefore, data might not actually get written to the file until later unless you tell it "write the buffer to disk now." This is traditionally done using flush()
. truncate()
evidently flushes before truncating.
精彩评论