簡體   English   中英

Python 截斷函數未按預期工作

[英]Python truncate function isnt working as expected

我對 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()

請幫忙

請參閱 文檔,重點是我的:

將流調整為給定的字節大小(如果未指定大小,則為當前位置) 當前流位置不會改變。

您需要調用.truncate(0)將文件截斷為零字節。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM