Python - store last processed line in file (text file loop and remember last line)
Hi,
when I iterate through a cycle a text file in a python script and the script crashes, the script continues from the beginning (from the first line) - I would need the script (cycle) to remember which line it ended on and from there continue to process. How would you easily solve it? Thank you
Hi,
it is possible to do this as in the example below.
Python loads the emails.txt file, which iterates emails line by line.
It saves the processed line in emails_state.txt.
When restarted, it continues where the script ended with the condition if not line in array_state:
when I iterate through a cycle a text file in a python script and the script crashes, the script continues from the beginning (from the first line) - I would need the script (cycle) to remember which line it ended on and from there continue to process. How would you easily solve it? Thank you
REPLY
Hi,
it is possible to do this as in the example below.
Python loads the emails.txt file, which iterates emails line by line.
It saves the processed line in emails_state.txt.
When restarted, it continues where the script ended with the condition if not line in array_state:
def getEmail(self):
# if exist file
try:
f = open("emails_state.txt")
# create temp file
except IOError:
with open("emails_state.txt", "w") as create_file:
create_file.write('')
# get first and last line
with open("emails_state.txt", "r") as file:
first_line = file.readline()
for last_line in file:
pass
# create array
with open("emails_state.txt", "r") as file:
array_state = file.readlines()
# file loop
fileHandler = open ("emails.txt", "r")
while True:
line = fileHandler.readline()
if not line :
break;
if not line in array_state:
print(line.strip())
with open("emails_state.txt", "a") as es:
es.write(line)
time.sleep(1)
# file close
fileHandler.close()