[英]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.