views:

89

answers:

2

So here's the problem I have,

I can find the Search Term in my file but at the moment I can only print out the line that the Search Term is in. (Thanks to Questions posted by people earlier =)). But I cannot print out all the lines to the end of the file after the Search Term. Here is the coding I have so far:-

search_term = r'\b%s\b' % search_term

for line in open(f, 'r'):
 if re.match(search_term, line):
     print line,

Thanks in advance!

A: 

You could set a boolean flag, e.g. "found = True"; and do a check for found==True, and if so print the line.

Code below:

search_term = r'\b%s\b' % search_term

found = False;
for line in open(f, 'r'):
        if found==True:
            print line,
        elif re.match(search_term, line):
            found = True;
            print line,

To explain this a bit: With the boolean flag you are adding some state to your code to modify its functionality. What you want your code to do is dependent on whether you have found a certain line of text in your file or not, so the best way to represent such a binary state (have I found the line or not found it?) is with a boolean variable like this, and then have the code do different things depending on the value of the variable.

Also, the elif is just a shortening of else if.

Roman Stolper
+1  A: 

It can be much improved if you first compile the regex:

search_term_regex = re.compile(r'\b%s\b' % search_term)

found = False
for line in open(f):
    if not found:
        found = bool(search_term_regex.findall(line))
    if found:
        print line,

Then you're not repeating the print line.

Peter Bengtsson