Tom Murley
Tom Murley

Reputation: 1004

How would I iterate onto the next line of a file within a nested loop using "for line" in fileinput?

I have eliminated some of the nested loops for simplicity of the example.

I am iterating over a file line-by-line using fileinput. If the line meets a certain condition I want it to replace all future lines with '' until it meets the condition again.

import re
import fileinput
with fileinput.FileInput("survey.qsf", inplace=True, backup='.bak') as file:
    for line in file:
        if re.match(r'l'+datamap[i][2]+'.*$',line)!=None:
            line=re.sub(r'.*$','',line)
            while re.match(r'lQID\d*$',line)==None:
                line=re.sub(r'.*$','',line)
                next(line)

I used "next(line)" as a placeholder as I can't figure out how to iterate to the next line without breaking out of the inner loop.

I want to be able to iterate through the lines to have:

lQID44
xyz
xyz
lQID45

output as:

[blank line]
[blank line]
[blank line]
lQID45

Thanks.

Upvotes: 1

Views: 263

Answers (1)

chepner
chepner

Reputation: 531235

next takes the iterator as its argument.

while re.match(r'lQID\d*$',line)==None:
    line=re.sub(r'.*$','',line)
    try:
        line = next(file)  # Not next(line)
    except StopIteration:
        break

As an aside, there's no need to use re.sub to replace the entire line with an empty string; line = '' would suffice.

(Also, assigning to line doesn't make changes to the actual file; inplace=True just means that you can write to file as well as read from it, but you have to explicitly write to the file, using print or file.write.)

Upvotes: 4

Related Questions