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

关于write()和truncate()的Python问题,python,terminal,Python,Terminal,我在mac上的终端,我正在学习如何打开、关闭、读取和删除文件 当我设定 f = open("sample.txt", 'w') 然后点击f.truncate()删除内容 但是,当我执行f.write()时,它不会在文本文件中更新。它仅在我执行f.truncate()之后更新 我想知道为什么会发生这种情况(我以为f.truncate()应该删除文本!)?为什么在我键入f.write()时文本编辑器不会自动更新?出于性能原因,文件的输出会被缓冲。因此,除非您告诉文件“立即将缓冲区写入磁盘”,否则数

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

当我设定

f = open("sample.txt", 'w')
然后点击
f.truncate()
删除内容

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


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

出于性能原因,文件的输出会被缓冲。因此,除非您告诉文件“立即将缓冲区写入磁盘”,否则数据可能直到稍后才会写入文件。这通常是使用
flush()
完成的
truncate()
显然会在截断之前刷新。

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

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

让我们看一个例子:

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

太好了,谢谢。另外,在我使用write函数之后,truncate()似乎不会删除内容。如何删除内容(我目前正在关闭python并重新打开它以截断内容)?
truncate()
默认情况下截断到当前位置。尝试
truncate(0)
将其完全清空。太好了,谢谢。另外,在我使用write函数之后,truncate()似乎不会删除内容。如何删除内容(我目前正在做的是关闭python并重新打开它以截断内容)??