pythonfilefile-handlingstopiteration

StopIteration given by a file iteration that uses nested loops


I'm having some issues with the following block of code. What I'm trying to do is go through a file line by line, and pull out the lines following a line that contains ".W", until it reaches a line that starts with ".I"

with open("cran.all.1400","r") as abstracts:
abstract_list = []
for line in abstracts:
    if (line.startswith(".W")):
        abstract_string = ""
        while not (line.startswith('.I')):
            abstract_string = abstract_string + line
            abstracts.next()
        abstract_list.append(abstract_string)

I've encountered the StopIteration, and some googling has shown me that this occurs when .next() has no value, but I'm not sure how I should be writing this code then.

What I'm unsure of specifically, is how to have the while loop continue going through the lines, and have the for loop pick up where the while loop left off.


Solution

  • Use a flag in the for-loop:

    with open("cran.all.1400") as abstracts:
        inside = False
        abstract_list = []
        for line in abstracts:
            if line.startswith(".W"):
                inside = True
                abstract_list.append("")
            elif line.startswith(".I"):
                inside = False
            elif inside:
                abstract_list[-1] += line