为什么访问模式r +不允许截断并附加新数据而不是覆盖?

问题描述 投票:0回答:1

我已经检查了一下,但找不到我的问题的答案。它与Python中read()函数中的访问模式r +有关。我

设置如下:

  1. 我有一个test.txt文件,例如包含三行,分别包含11、12、13。

  2. 我有包含以下内容的code.py文件:

script, filename = argv

print("Opening the file...")
target=open(filename, 'r+')

print("currently in the file: ")
print(target.read())

print("Truncating the file")
target.truncate()

print("input three lines.")
line1 = input("line 1: ")
line2 = input("line 2: ")
line3 = input("line 3: ")

target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")

print("Now we close the file. Bye.")
target.close()
  1. 我从命令行运行:python code.py test.txt

read()函数已执行,我看到将11,12,13输出到命令窗口。

我假设truncate()也运行。

然后输入三行,例如66、67、68。

[当我打开test.txt文件时,我在11,12,13,66,67,68一栏中看到。

我希望truncate()删除test.txt文件中的所有数据,然后r +在其中写入66,67,68,而不是附加这些行。

有人可以向我解释为什么会这样吗?

我不理解逻辑,访问模式的描述也无济于事(嗯,我知道w / w +会在打开文件时截断(=删除所有数据)。

并且,如果我将target.truncate()替换为target.truncate(0),则删除11,12,13,然后在66、67、68一栏中看到66缩进了10个空格。这是怎么回事?

谢谢你。

python python-3.x io truncate
1个回答
0
投票

因为未指定大小,所以truncate会缩小到当前位置。在r模式下,它是文件的末尾。试试truncate(0)

© www.soinside.com 2019 - 2024. All rights reserved.