我已经查过了,但我找不到问题的答案。它是关于Python ()函数中的访问模式r+的。我
设置如下:
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()执行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个空格。这里发生了什么??
提前谢谢你。
发布于 2019-12-17 13:44:16
因为您没有指定任何大小,所以truncate减少到当前位置。在r模式下,它是文件的结尾。试试truncate(0)
https://stackoverflow.com/questions/59375373
复制相似问题