Python 如何在使用"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')它的内容将被删除,但我想尽可能保持文件打开以提高效率。

最好的方法是什么?

在每次write之前seeking(并切换到线路缓冲以避免需要单独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

最新更新