【发布时间】:2020-01-17 06:02:12
【问题描述】:
我对 python 中的 truncate 函数有点困惑。 truncate 函数不应该清空文件并仅显示第二行输入吗?但在我的文件中,第一行和第二行输入都在程序结束后的文件中。
文件中的预期输出
Line2 input
文件中的当前输出
Line1 input Line2 input
如果我使用 .truncate(0),这就是我在文件中得到的内容
from sys import argv
script, filename = argv
print(f"Erasing the file {filename}")
print("Opening the file...")
# This empties and overrides the file when opening in w mode use 'a' to append to file
target = open(filename, 'w')
line = input("Input a line")
target.write(line)
print("Truncating ie erasing the file...")
target.truncate()
line2 = input("Input another line")
target.write(line2)
target.close()
请帮忙
【问题讨论】:
-
可能重复。在这里查看答案:stackoverflow.com/a/26917275/7977464
-
试试
truncate(0)。 -
truncate()删除了当前光标位置之后(第一行之后)的文件内容。它实际上什么都不做,因为光标在文件的末尾。 -
试过你们说的。请检查问题的编辑部分
标签: python python-3.x truncate