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



我已经检查过了,但我找不到问题的答案。 它是关于 Python 中 read(( 函数中的访问模式 r+。我

设置如下:

  1. 我有一个测试.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 测试.txt

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

我假设 truncate(( 也运行。

然后我输入三个新行,比如 66、67、68。

当我打开测试时.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 缩进了十个空格。这是怎么回事??

提前谢谢你。

因为您没有指定大小truncate减小到当前位置。在r模式下,它是文件的末尾。试试truncate(0)

最新更新