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

jcvanelst at gmail.com jcvanelst at gmail.com
Tue Jan 8 16:21:28 EST 2008


On 8 jan, 03:19, Horacius ReX <horacius.... at gmail.com> wrote:
> Hi,
>
> 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 ?
>
> Thanks

hi, i'm no python whizzkid, but you can do a lot with the .index
syntax. If you do something like this, it'll return the index of the
first character of your string as it is found in your file. Note that
if you read a file like this there will be some special characters for
new lines and the list structure that python uses, so if you want to
know the exact line you will have to find that out by playing with a
small file. You can always use a command like:  print s[12]
if you want to know the exact 12th character in your file
--------------------------------------------------------
infile = open("C:\\Users\\yourname\\Desktop\\", 'r')

f= yourfile.readlines()
s=str(f)
yourstring = s.index('mystring')
--------------------------------------------------------

good luck,

)a((o



More information about the Python-list mailing list