How to maintain the last index value in python list while doing iteration

Viewed 19

My scenario is, lets say I have a list1= ["a","b","c"] and this list is dynamic (data is getting appended). My requirement is I need to process the list data each day to eventhub but I should not upload all data each day.I just need to upload the delta.

my approach is

index=0
for i range(len(list1):
     ## upload
     index=index+1

I want to preserve the latest index value, for e.g. in first run index would be 2 and for next run index should be 3 not 0 as per above code. How should I proceed?

1 Answers

I'd simply create a local file file that stores the index. Next time you need it load it and get from there on, assuming you are using the array and the script locally and only have to upload the part of that array.

import os

index = 0
if os.path.isfile("indexFile.txt"):
    f = open("indexFile.txt" , "r")
    s = f.read()
    f.close()
try: index = int(s)
except: index = 0

print("index is: " + str(index))
print("do something with that index")
index += 1
print("store the index back to file")
f = open("indexFile.txt" , "w")
f.write(str(index))
f.close()
Related