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?