0

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?

Usman
  • 1,983
  • 15
  • 28
Sulli
  • 763
  • 1
  • 11
  • 33
  • Possible duplicate of [How to delete only the content of file in python](https://stackoverflow.com/questions/17126037/how-to-delete-only-the-content-of-file-in-python) –  Mar 13 '19 at 11:13

2 Answers2

1

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')
ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
  • I would add a `truncate` to handle the case where next line is shorter than previous one... – Serge Ballesta Mar 13 '19 at 15:35
  • @SergeBallesta: In the general case, yes, that would be correct. In this particular case, the checkpoint is a monotonically increasing number, so each newly written string will always be as long as, or longer than, the previous output, making it unnecessary to explicitly `truncate` (barring the off chance that you're using a text encoding so weird that the different numeric digits produced by stringifying an `int` encode to a variable number of bytes; if you know of such an encoding, let me know, and it'll be yet one more computer-related factoid to torture people with :-) ). – ShadowRanger Mar 13 '19 at 16:02
0

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

Mihai Andrei
  • 1,024
  • 8
  • 11