-4

I want to save a loop counter in an external file to be able to resume the loop where it ended in case it crashes or I stop before the end. So each for each loop turn I'd like to overwrite the first line with the counter. Now I know I can do that by calling open(file, 'w') everytime but I wonder if it will cause some problems.

ChiseledAbs
  • 1,963
  • 6
  • 19
  • 33

1 Answers1

1

This is a brute force solution, that is probably inefficient if you are dealing with a lot of iterators:

def write_to_file():
    for i in range(5):
        with open("temp", "w") as f:
            # change this to the command you want to store
            f.write("This is iteration {}\n".format(i))

    # checking the file contents, contains only last command
    with open("temp", "r") as f:
        print f.read()

Another way to approach it is to read the line and copy it over. See more from here: change first line of a file in python

Keeping the last line in a file can be problematic if your code crashes before writing the last line (so you have wrong data), or if you open the file every time again when you write, it has to do a lot of operations and can be slow.

Community
  • 1
  • 1
codeforwin
  • 51
  • 3
  • I did it by calling `open` at each loop turn at the end, I still don't know if it's the most efficient way to do it as people prefered to downvote instead of answering but thanks for the answer anyway. – ChiseledAbs Dec 12 '16 at 07:35