Skip to main content
 首页 » 编程设计

python之无法理解 Python 的 'truncate' 和 'write'

2024年10月25日9zlslch

我在 Python shell 中,我正在尝试了解基础知识。这是我输入的内容:

doc = open('test.txt', 'w') # this opens the file or creates it if it doesn't exist 
doc.write('blah blah') 
doc.truncate() 

我理解第一行。但是,在第二行中,不是应该向文件写入“blah blah”吗?它不会那样做。但是,当我对文件运行 truncate 函数时,突然出现“blah blah”。有人可以向我解释这个逻辑是如何工作的吗?

我认为 truncate 应该删除文件的内容?为什么它会显示之前的 write 行?

请您参考如下方法:

来自manual :

file.truncate([size])

[...] The size defaults to the current position [...]

所以当你打开并写入文件时,当前位置就是文件的末尾。基本上,您是从文件末尾截断的。因此,除了实际刷新缓冲区并将文本写入磁盘之外,没有其他效果。 (truncate 在截断前刷新)

尝试使用truncate(0);这将清空文件。