Python Forum

Full Version: lifetime cycle counter
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I made the generic code to do the job i want, but i want to also keep track of the total number of cycles the machine does. to keep this data when the computer turns off i need to save the cycle count value to a .txt document, then read it every time a cycle starts, add 1 to it when a cycle completes, delete the old value, and save the new one. repeat this every time a cycle happens.

i use a for loop to govern the number of cycles to be run based off of external input from another program, and it works. in the for loop i have a print(1 cycle) so i can see that it runs the correct number of cycles, which it does. However, when i callout my cycle counter function within this for loop it only runs the function once while still running everything else the correct number of times.

this means that in my .txt file the number only increases by 1 every time instead of increasing by how many cycles it did.

ill put in the code, but it wont make much sense to you without the other program too. basically create the .txt file "Cycle.txt" and put in any number and a "lifecounter.txt" file and put in 0 then the important part will work.

def countmath():
    counttxt = open('lifecounter.txt', 'r+')
    for line in counttxt:
        countlist.append(line)
    D = countlist[0]
    counter = int(D)
    counter += 1  # adds 1 to the counted value
    counttxt.truncate()  # deletes previous file data
    counttxt.close()

    E = str(counter)
    counttxt1 = open('lifecounter.txt', 'r+')
    counttxt1.write(E)
    counttxt1.close()


store=[]             #creates empty list
cycles= open('Cycle.txt','rt')          #opens "cycle.txt" file under the name "cycles" with the intention to read text
for line in cycles:      #reads each line of .txt file seperately 1 after the other
    store.append(line)    #adds the currently read line to the list "store"

A= store[1]  #Assigns the variable "A" the value of line 1 in the newly formed list
B= store[2]
C= store[3]

cyclesD=int(A)    #convert list items to integer values and assign them to new variables
rateD=int(B)
powerD=int(C)

countlist = []

for lifecount in range (cyclesD):     #loops the process the number of times as in the parenthasis.
    print("1 Cycle")
    countmath()



if powerD==(1):
    print("shutting down")
    exit()
if powerD==(0):
    print("Job Complete")
    exit()
i know this is a cluster, but im just learning