Use a state machine. That means, once you see your opening pattern, set a state so you know that the following lines are now relevant to you. Then keep looking out for the ending pattern to turn it off:
def printlines():
# this is our state
isWithin = False
with open('text.txt') as f:
for line in f:
# Since the line contains the line breaking character,
# we have to remove that first
line = line.rstrip()
# check for the patterns to change the state
if line == "***a":
isWithin = True
elif line == "---a":
isWithin = False
# check whether we’re within our state
elif isWithin:
print line
Since we only print once we’re in the isWithin
state, we can easily skip any part out side of the ***a
/---a
pattern. So processing the following file would correctly print out Hello
and World
and nothing else:
Foo
***a
Hello
---a
Bar
***a
World
---a
Baz
Also, you should use the with
statement to open your file, and iterate over the file object directly instead of reading it and calling splitlines()
. That way you make sure that the file is properly closed, and you only ever read one line after another, making this more memory efficient.