我在删除文件内容时遇到问题。我有一个文件,里面有'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'
。在
在
handle.read()
之后,您处于文件的末尾,因此没有任何内容可以从这里截断。在handle.read()
之后发出handle.seek(0)
。然后将数据写入文件,然后根据需要截断。在From the docs:
在调用
handle.read()
之后调用handle.truncate()
,此时当前位置是文件的结尾,因此Python会将文件截断为当前大小,但不会执行任何操作。您需要将0作为参数传递给truncate
:handle.truncate(0)
。在根据^{} 的文档,默认值为当前位置。您需要通过
0
。在相关问题 更多 >
编程相关推荐