首页 > 解决方案 > Python truncate 函数未按预期工作

问题描述

我对python中的截断函数有点困惑。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()

请帮忙

标签: pythonpython-3.xtruncate

解决方案


请参阅文档,强调我的:

将流的大小调整为以字节为单位的给定大小(如果未指定大小,则调整为当前位置)。当前的流位置没有改变。

您需要调用.truncate(0)以将文件截断为零字节。


推荐阅读