关于write()和truncate()的Python问题

时间:2011-04-09 18:56:44

标签: python terminal

我在Mac上的终端,我正在学习如何打开,关闭,读取和删除文件。

当我设置

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

然后点击f.truncate()内容删除。

但是,当我执行f.write()时,它不会在文本文件中更新。它只在我f.truncate()之后更新。

我想知道为什么会发生这种情况(我认为f.truncate()应该删除文本!)?当我输入f.write()时,为什么文本编辑器不会自动更新?

3 个答案:

答案 0 :(得分:4)

f.write()写入Python进程自己的缓冲区(类似于C fwrite()函数)。但是,在您调用f.flush()f.close()或缓冲区填满之前,数据实际上并未刷新到OS缓冲区中。完成后,所有其他应用程序都可以看到数据。

请注意,操作系统执行另一层缓冲/缓存 - 由所有正在运行的应用程序共享。刷新文件时,会将其写入这些缓冲区,但在一段时间过后或调用fsync()时尚未写入磁盘。如果您的操作系统崩溃或计算机断电,此类未保存的更改将会丢失。

答案 1 :(得分:4)

让我们看一个例子:

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

答案 2 :(得分:2)

出于性能原因,缓冲输出到文件。因此,除非您告诉它“立即将缓冲区写入磁盘”,否则数据实际上可能不会被写入文件。传统上使用flush()完成此操作。 truncate()明显在截断之前刷新。