Python 截断方法大小参数行为

标签 python file

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

现在,我需要删除较旧的内容并写回更新的内容,因此为此,我使用 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 所做的)。当您编写时如何解决这个问题可能取决于操作系统(在我的计算机上,第一个示例有效!)但是您始终可以让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/

相关文章:

python - Python 和 Numpy 中自定义 NaN float 的行为

c# - Azure 文件存储中的 System.IO 命名空间

c - 如何发现文件夹中存在哪些文件

python - 扭曲回溯中的 "<exception caught here>"行是什么意思?

python - 使用 setuptools 仅安装 .pyc(python 编译)

python - Phantomjs 通过 python 中的 selenium

file - 将包含目录的 SVN 修改文件复制到另一个目录

java - 如何获取我要使用多部分上传的文件的名称

python - 调用嵌套函数后发生NameError

python - 使用 Python 将 XML 转为 MYSQL