简体   繁体   English

用“ with”打开文件后,Python如何删除文件

[英]Python how to erase a file once it's opened with “with”

I'm saving the loop iteration number of my script to a checkpoint file: 我将脚本的循环迭代号保存到检查点文件中:

with open('checkpoint.txt', 'w') as checkpoint_file:
    for i range(1000):
        //do stuff
        checkpoint_file.write(str(i) + '\n')

This will write a new line in my file for each iteration. 这将为每次迭代在我的文件中写入新行。

What I would like is to have only one line with the last iteration number when I interrupt the script, so I would like to erase the content of "checkpoint.txt" file, and then write my iteration number on the first line (or directly replace the first line if this is possible). 我想在中断脚本时只将最后一个迭代编号作为一行,因此我想擦除“ checkpoint.txt”文件的内容,然后将我的迭代编号写在第一行(或直接写入)如果可能,请替换第一行)。

I know that if I close the file and then open it again with with open('checkpoint.txt', 'w') its content will be erased, but I'd like to keep the file opened if possible for efficiency. 我知道,如果我关闭文件,然后with open('checkpoint.txt', 'w')再次打开它with open('checkpoint.txt', 'w')其内容将被删除,但我想尽可能保持文件打开以提高效率。

What's the best way to do that? 最好的方法是什么?

seek ing before each write (and switch to line buffering to avoid the need to flush separately) will do this: 在每次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')

Seek to the start of the file before each write. 每次写入之前,请先搜索文件的开头。 See https://docs.python.org/2/library/stdtypes.html?highlight=seek#file.seek 参见https://docs.python.org/2/library/stdtypes.html?highlight=seek#file.seek

How are you interrupting the script? 您如何打断脚本?

If it's something like the KeyboardInterrupt , then you can try the following: 如果它类似于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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM