Look for a string on a file and get its line number

Wildemar Wildenburger lasses_weil at klapptsowieso.net
Tue Jan 8 06:53:37 EST 2008


Jeroen Ruigrok van der Werven wrote:
> line_nr = 0
> for line in big_file:
>     line_nr += 1
>     has_match = line.find('my-string')
>     if has_match > 0:
>         print 'Found in line %d' % (line_nr)
> 
Style note:
May I suggest enumerate (I find the explicit counting somewhat clunky) 
and maybe turning it into a generator (I like generators):

def lines(big_file, pattern="my string"):
     for n, line in enumerate(big_file):
         if pattern in line:
             print 'Found in line %d' % (n)
             yield n

or for direct use, how about a simple list comprehension:

lines = [n for (n, line) in enumerate(big_file) if "my string" in line]

(If you're just going to iterate over the result, that is you do not 
need indexing, replace the brackets with parenthesis. That way you get a 
generator and don't have to build a complete list. This is especially 
useful if you expect many hits.)

Just a note.

regards
/W



More information about the Python-list mailing list