简体   繁体   English

Python不使用truncate擦除文件内容

[英]Python not erasing contents of file with truncate

I am having problems erasing file contents. 我在擦除文件内容时遇到问题。 I have a file with 'ABC' in it. 我有一个带有'ABC'的文件。 I open it up and truncate() to clear everything from the file and then write new contents to it. 我打开它并进行truncate()清除文件中的所有内容,然后向其中写入新内容。 But whatever I write just gets appended to what was previously there. 但是我写的任何东西都被附加到以前的内容之后。

>>> handle=open('test.txt', 'r+')
>>> stuff = handle.read()
>>> stuff
'ABC'
>>> handle.truncate()
>>> handle.write('DEF'+stuff)
>>> handle.close()
>>> handle=open('test.txt', 'r+')
>>> handle.read()
'ABCDEFABC'

I think I should be getting 'DEFABC' but instead I get 'ABC' with 'DEFABC' appended to the end. 我认为我应该得到'DEFABC'但我得到的是'ABC'加上'DEFABC'

After handle.read() , you are at the end of the file, so there's nothing to truncate from here. handle.read() ,您位于文件的结尾,因此没有什么可以从这里截断的。 Issue handle.seek(0) after handle.read() . handle.read()之后发出handle.seek(0) handle.read() Then write your data to the file, then truncate if necessary. 然后将数据写入文件,然后在必要时截断。

From the documentation of truncate , the default value is the current position. truncate的文档中,默认值是当前位置。 You need to pass 0 . 您需要传递0

Truncate the file's size. 截断文件的大小。 If the optional size argument is present, the file is truncated to (at most) that size. 如果存在可选的size参数,则文件将被截断为(最多)该大小。 The size defaults to the current position. 尺寸默认为当前位置。 The current file position is not changed. 当前文件位置未更改。 Note that if a specified size exceeds the file's current size, the result is platform-dependent: possibilities include that the file may remain unchanged, increase to the specified size as if zero-filled, or increase to the specified size with undefined new content. 请注意,如果指定的大小超过文件的当前大小,则结果取决于平台:可能的情况是文件可能保持不变,增大为指定大小(好像是零填充的)或使用未定义的新内容增大到指定的大小。 Availability: Windows, many Unix variants. 可用性:Windows,许多Unix变体。

From the docs: 从文档:

file.truncate([size])

Truncate the file's size. 截断文件的大小。 If the optional size argument is present, the file is truncated to (at most) that size. 如果存在可选的size参数,则文件将被截断为(最多)该大小。 The size defaults to the current position. 尺寸默认为当前位置。

You call handle.truncate() after calling handle.read() , at which time the current position is the end of the file, so Python truncates the file to its current size, which does nothing. 您在调用handle.truncate()之后调用handle.read() ,此时当前位置是文件的末尾,因此Python handle.read()文件截断为当前大小,这不会执行任何操作。 You need to pass 0 as the argument to truncate : handle.truncate(0) . 您需要传递0作为truncate的参数: handle.truncate(0)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM