-1

My txt file has:

/aaa/AB01_Z
/bbb/AB02_Z
/ccc/AB03_Z
/ddd/AB04_Z

Patterns of my interest are:

AB01, AB03

I would like to print lines with the pattern in this order.

I tried:

import re

lst = ['AB01', 'AB03']
f = open('myfile.txt')

for pattern in lst:
    for line in f:
        if re.search(pattern, line):
            print(line)

However, this only returns '/aaa/AB01_Z'.

If I open the file under the loop for the pattern list, I get '/aaa/AB01_Z' and '/ccc/AB03_Z' as expected:

for pattern in lst:
    f = open('myfile.txt')
    for line in f:
        if re.search(pattern, line):
            print(line)

Why does not the loop for pattern run in the first case?

aho
  • 79
  • 1
  • 3
  • 8
  • 1
    You're at the end of the file after the first inner loop. You have to rewind the file to its beginning when starting on next steps of the outer loop. –  Dec 26 '16 at 00:04
  • 1
    You can replace `if re.search(pattern, line)` with `if pattern in line:`, by the way. Regular expressions aren't adding any value here. – TigerhawkT3 Dec 26 '16 at 00:06
  • Thanks all. Ah, yes. I oversimplified my original question to a point where regular expression is pointless. – aho Dec 26 '16 at 00:19

1 Answers1

1

When you do for line in f you are getting your information an iterator providing you with the lines of f, as long as there are any. In your first case, the iterator completes runs through all of the lines while working on the first pattern, and provides you with nothing once you get to the second one.

fuglede
  • 17,388
  • 2
  • 54
  • 99