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

Python 为什么访问模式为r+;不允许截断并追加新数据而不是覆盖?,python,python-3.x,io,truncate,Python,Python 3.x,Io,Truncate,我查过了,但找不到我问题的答案。 它是关于Python中read()函数中的访问模式r+。我 设置如下所示: 我有一个test.txt文件,包含三行,分别是11、12、13 我的code.py文件包含以下内容: 我从命令行运行:python code.py test.txt 执行read()函数后,我看到11,12,13输出到命令窗口 我想truncate()也会运行 然后我输入三个新行,比如66,67,68 当我打开test.txt文件时,我会看到第11、12、13、66、67、68列 我希望

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

设置如下所示:

  • 我有一个test.txt文件,包含三行,分别是11、12、13

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

  • 我从命令行运行: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(0)替换target.truncate(),那么11,12,13将被删除,我在一列66,67,68中看到66缩进了十个空格。这里发生了什么事


    提前谢谢。

    因为您没有指定大小
    截断
    缩小到当前位置。在
    r
    模式下,它是文件的结尾。尝试
    截断(0)

    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()