gpt4 book ai didi

Python 截断方法大小参数行为

转载 作者:太空宇宙 更新时间:2023-11-04 02:51:46 26 4
gpt4 key购买 nike

我正在尝试通过替换字符串的内容并写入更新的内容来更新文件中的内容。

现在要做的是,我需要删除旧的内容并写回更新的内容,为此,我使用了truncate 方法。

根据 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!

现在的问题是,

  1. 为什么 truncate(0) 调用导致文件以不同的格式写入?
  2. 我已将大小参数从 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 所做的)。当你 write 时如何解决这个问题可能取决于操作系统(在我的电脑上第一个例子成功了!)但是你总是可以让 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com