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

Jeroen Ruigrok van der Werven asmodai at in-nomine.org
Tue Jan 8 03:33:02 EST 2008


-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.

-- 
Jeroen Ruigrok van der Werven <asmodai(-at-)in-nomine.org> / asmodai
イェルーン ラウフロック ヴァン デル ウェルヴェン
http://www.in-nomine.org/ | http://www.rangaku.org/
If you think that you know much, you know little... 



More information about the Python-list mailing list