简体   繁体   中英

Start file processing from line with certain string in Python

I am writing a Python (specifically 3.x) script to read names from a file and process them. Lets assume I have the following text in the file names.txt which looks something like this:

Rebecca Rivera
Ralph   Turner
Katherine   Green
Douglas Perry
Kenneth Carter
David   King
Debra   Johnson
Bruce   Ross
Victor  Lewis
Louis   Young

The script might crash at some random point within the file after it starts reading from the top of the file to the bottom ( Note: this is not the issue) . I can know exactly at what name the script failed and save it, but regardless would like to iterate my script through every name. Hence, if the script runs through the whole file, there is no issue and no name is saved, but if it is not the EOF, the name that was being processed as the script fail should be saved.

The function I am using to process the names is called by giving it a list with all the names, and is as follows:

def processNames(names):
    for name in names:
        try:
            processing(name)
        except:
            print('Failed. Will try in next script run')
            break

How can I use the name at which the script failed, and run the next iteration starting from the name at which it previously failed?

You can do it with an additional counter variable to record where it crashed. Code:

def processNames(names):
    counter=0
    for index, name in enumerate(names):
        if index>counter:
            try:
                processing(name)
            except:
                print('Failed. Will try in next script run')
                counter=index

Reflecting on the comments this might be better:

def processNames(names, counter):
    for index, name in enumerate(names):
        if index>counter:
            try:
                processing(name)
            except:
                print('Failed. Will try in next script run')
                counter=index
    return whateveryouneed, counter

Also might want to look up for-else loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM