[英]Python how to erase a file once it's opened with “with”
我將腳本的循環迭代號保存到檢查點文件中:
with open('checkpoint.txt', 'w') as checkpoint_file:
for i range(1000):
//do stuff
checkpoint_file.write(str(i) + '\n')
這將為每次迭代在我的文件中寫入新行。
我想在中斷腳本時只將最后一個迭代編號作為一行,因此我想擦除“ checkpoint.txt”文件的內容,然后將我的迭代編號寫在第一行(或直接寫入)如果可能,請替換第一行)。
我知道,如果我關閉文件,然后with open('checkpoint.txt', 'w')
再次打開它with open('checkpoint.txt', 'w')
其內容將被刪除,但我想盡可能保持文件打開以提高效率。
最好的方法是什么?
在每次write
之前進行seek
(並切換到行緩沖以避免單獨flush
)將這樣做:
# buffering=1 means you automatically flush after writing a line
with open('checkpoint.txt', 'w', buffering=1) as checkpoint_file:
for i in range(1000):
//do stuff
checkpoint_file.seek(0) # Seek back to beginning of file so next write replaces contents
checkpoint_file.write(str(i) + '\n')
每次寫入之前,請先搜索文件的開頭。 參見https://docs.python.org/2/library/stdtypes.html?highlight=seek#file.seek
您如何打斷腳本?
如果它類似於KeyboardInterrupt
,那么您可以嘗試以下操作:
with open('checkpoint.txt', 'w') as checkpoint_file:
for i range(1000):
# do stuff
try:
checkpoint_file.write(str(i) + '\n')
except KeyboardInterrupt:
checkpoint_file.seek(0)
checkpoint_file.truncate()
checkpoint_file.write(str(i))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.