Initialize counter with result from previous run saved to a file

Question:

I am using a program using python that counts pulses with the GPIO and stores them in a text file. How can I update that program in such a way that when the program is restarted or else update the rapsberry pi, the counter will continue to count from the last count that was before?

counter = 0

def my_callback2(channel)

global counter
counter = counter + 1
print counter

file = open("testfile.txt", "w")
file.write(str(counter))

file.close()
with open('testfile.txt', 'r') as f:
    first_line = f.readline()

print "switch press detected"
Asked By: Andrew Attard

||

Answers:

There must be easier ways but this will do it:

order_idFile = open('some_file.txt', 'r') # open file for reading
order_id = int(order_idFile.read().strip()) # read file contents, strip it and convert a str to int
order_idFile.close() # close file
order_id += 1 # add 1 to current number
order_idFile = open('some_file.txt', 'w') # open file for writing 
order_idFile.write(str(order_id)) # convert int to str and write to file
order_idFile.close() # close file

Note:
some_file.txt must have a valid number (0 perhaps?) the first time you run the script.

Answered By: Pedro Lobito
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.