简体   繁体   中英

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).

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.

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:

# 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

How are you interrupting the script?

If it's something like the KeyboardInterrupt , then you can try the following:

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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