我试图通过替换字符串的内容并写入更新的内容来更新文件内的内容。
现在,我需要删除较旧的内容并写回更新的内容,因此为此,我使用 truncate
方法。
根据截断
的文档
file. truncate([size])
size Optional. If the optional size argument is present, the file is truncated to (at most) that size. The size defaults to the current position.
现在,我有两个案例,我无法理解发生了什么?
def fileIsWritingInBinary():
with open("hello.txt", "r+") as f:
fileContent = f.read()
f.truncate(0) # used different size argument
# update new content
fileContent = fileContent.replace("World", "StackOverFlow")
# write updated content
f.write(fileContent)
文件 hello.txt
中写入的内容采用不同的格式,即
4865 6c6c 6f00 0000 0000 0000 0048 656c
6c6f 2c20 576f 726c 6421
但是按照如下所述进行更改后,它可以正常工作,即在 truncate
调用之前添加 f.seek(0)
。
def fileIsWritingInBinary():
with open("hello.txt", "r+") as f:
fileContent = f.read()
f.seek(0) // line added
f.truncate()
# update new content
fileContent = fileContent.replace("World", "StackOverFlow")
# write updated content
f.write(fileContent)
# hello.txt content
# Hello, StackOverFlow!
现在的问题是,
- 为什么
truncate(0)
调用会导致文件以不同的格式写入? - 我已将大小参数从
0
更改为不同的数字,但仍然得到相同的结果。
最佳答案
如果你查看 truncate
的文档在 io
模块中,您可以看到发生了什么:
Resize the stream to the given size in bytes (or the current position if size is not specified). The current stream position isn’t changed. This resizing can extend or reduce the current file size. In case of extension, the contents of the new file area depend on the platform (on most systems, additional bytes are zero-filled). The new file size is returned.
(强调我的)
因此,即使您截断了流,您也没有更改流中的位置(这就是 seek
所做的)。当您编写
时如何解决这个问题可能取决于操作系统(在我的计算机上,第一个示例有效!)但是您始终可以让Python告诉
您流中的当前位置:
with open("hello.txt", "r+") as f:
fileContent = f.read()
print(f.tell())
f.truncate(0)
print(f.tell())
f.seek(0)
print(f.tell())
# update new content
fileContent = fileContent.replace("World", "StackOverFlow")
# write updated content
f.write(fileContent)
print(f.tell())
关于Python 截断方法大小参数行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43654921/