Sulli
Sulli

Reputation: 821

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?

Upvotes: 0

Views: 76

Answers (2)

ShadowRanger
ShadowRanger

Reputation: 155313

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

Upvotes: 1

Mihai Andrei
Mihai Andrei

Reputation: 1034

Seek to the start of the file before each write. See https://docs.python.org/2/library/stdtypes.html?highlight=seek#file.seek

Upvotes: 0

Related Questions