Python 为什么访问模式为r+;不允许截断并追加新数据而不是覆盖?
我查过了,但找不到我问题的答案。 它是关于Python中read()函数中的访问模式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列 我希望
提前谢谢。因为您没有指定大小
截断
缩小到当前位置。在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()