无法理解Python'截断'并且'写'

时间:2014-11-13 20:12:05

标签: python file file-io

我在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()

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

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

3 个答案:

答案 0 :(得分:2)

来自manual

  

file.truncate([大小])

     

[...]大小默认为当前位置[...]

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

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

答案 1 :(得分:0)

如果您没有指定尺寸参数。该功能占据当前位置。

如果要删除文件内容:

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

或更好:

with open('test.txt', 'w') as doc:
    doc.write('blah blah')
    doc.truncate(0)

答案 2 :(得分:0)

与上下文管理器相同:

with open('test.txt', 'w') as doc:
    doc.write('blah blah')
    # doc.truncate() 

上面将截断到当前位置,该位置位于文件的末尾,这意味着它不会截断任何内容。

这样做,它会在第0个字节截断文件,有效地清除它。

    doc.truncate(0) 

我从你的评论中看到你可能仍然遇到麻烦,可以通过使用上下文管理器解决问题:

>>> def foofile():
...     with open('/temp/foodeleteme', 'w') as foo:
...         foo.write('blah blah blah')
...         foo.truncate(0)
...     with open('/temp/foodeleteme') as foo:
...         print foo.read()
...         
>>> foofile()

什么都不打印。

相关问题