Python无法使用truncate清除文件内容

2024-09-23 06:31:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我在删除文件内容时遇到问题。我有一个文件,里面有'ABC'。我打开它,truncate()清除文件中的所有内容,然后向其中写入新内容。但无论我写什么,都会附加到之前的内容中。在

>>> 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'

我想我应该得到'DEFABC',但是我得到了'ABC',并在末尾附加了'DEFABC'。在


Tags: 文件testtxt内容closereaddefopen
3条回答

handle.read()之后,您处于文件的末尾,因此没有任何内容可以从这里截断。在handle.read()之后发出handle.seek(0)。然后将数据写入文件,然后根据需要截断。在

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. The size defaults to the current position.

在调用handle.read()之后调用handle.truncate(),此时当前位置是文件的结尾,因此Python会将文件截断为当前大小,但不会执行任何操作。您需要将0作为参数传递给truncate:handle.truncate(0)。在

根据^{}的文档,默认值为当前位置。您需要通过0。在

Truncate the file’s size. If the optional size argument is present, the file is truncated to (at most) that 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.

相关问题 更多 >