Python截断函数无法正常工作

问题描述 投票:0回答:1

我对python中的truncate函数有些困惑。截断函数是否不应该清空文件并仅显示输入的第二行?但是在我的文件中,程序结束后第一和第二输入行都在文件中。

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()
python python-3.x truncate
1个回答
0
投票

请参见the docs,重点是:

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

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

© www.soinside.com 2019 - 2024. All rights reserved.