EvelynZ
EvelynZ

Reputation: 73

How to run a function while ignoring several lines in Python?

I have a file that looks like this:

a
b
str1
c
d
str2
e
f

Now I want to run a re.sub() function that applies to lines in this file except lines between "str1" and "str2" (i.e. only apply to line "a", "b", "e" and "f"). How should I do this? Thanks!

Upvotes: 2

Views: 67

Answers (2)

Aaron
Aaron

Reputation: 11075

you can use a loop within a loop to skip lines while iterating over a file

with open(infile) as f:
    for line in f:
        if line == 'str1':
            for line in f:
                if line=='str2': break
        else:
            re.sub(line)

Upvotes: 0

mmghu
mmghu

Reputation: 619

between_strings = False

for line in lines:
    if line == 'str1':
        between_strings = True
    elif line == 'str2':
        between_strings = False
        continue
    if not between_strings:
        re.sub(line)

Here is how I would implement this. It would check each line, and when it finds str1, set between_strings to True. When it is True it would skip lines. Once it finds str2 it will begin reading lines again. Let me know if you have any questions.

Upvotes: 2

Related Questions