Python - store last processed line in file (text file loop and remember last line)

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

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()

Související obsah

programovani

python

file

loop

Komentáře

Vaše reakce na Python - zpracování dat ze souboru cyklem - jak uložit poslední dokončený řádek a pokračovat dále

Reference

Podívejte se na naše reference

Prohlédnout

Aplikace

Podívejte se na naše aplikace

Prohlédnout

Co umíme?

Podívejte se co umíme

Prohlédnout

Co umíme?

Vytváříme sofistikované aplikace pro náročné

Od webových aplikací přes android až po převodové můstky či složité informační systémy.

Podívejte se k nám

Máte ještě čas? Podívejte se na další rubriky

Tento web používá soubory cookie. Dalším procházením tohoto webu vyjadřujete souhlas s jejich používáním.. Více informací zde.