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

John Machin sjmachin at lexicon.net
Tue Jan 8 09:46:56 CET 2008


On Jan 8, 7:33 pm, Jeroen Ruigrok van der Werven <asmo... at in-
nomine.org> wrote:
> -On [20080108 09:21], Horacius ReX (horacius.... 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:

Make that >=

| >>> 'fubar'.find('fu')
| 0
| >>>

>         print 'Found in line %d' % (line_nr)




More information about the Python-list mailing list