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

Martin Marcher martin at marcher.name
Tue Jan 8 05:01:03 EST 2008


Jeroen Ruigrok van der Werven wrote:

> -On [20080108 09:21], Horacius ReX (horacius.rex at gmail.com) wrote:
>>I have to search for a string on a big file. Once this string is
>>found, I would need to get the number of the line in which the string
>>is located on the file. Do you know how if this is possible to do in
>>python ?
> 
> (Assuming ASCII, otherwise check out codecs.open().)
> 
> big_file = open('bigfile.txt', 'r')
> 
> 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)
> 
> Something to this effect.

apart from that look at the linecache module. If it's a big file it could
help you with subsequent access to the line in question

hth
martin

-- 
http://noneisyours.marcher.name
http://feeds.feedburner.com/NoneIsYours

You are not free to read this message,
by doing so, you have violated my licence
and are required to urinate publicly. Thank you.




More information about the Python-list mailing list