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

Tim Chase python.list at tim.thechases.com
Tue Jan 8 14:15:57 CET 2008

>> 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 ?
> This should be reasonable:
>>>> for num, line in enumerate(open("/python25/readme.txt")):
> 	if "Guido" in line:
> 		print "Found Guido on line", num
> 		break
> Found Guido on line 1296

Just a small caveat here:  enumerate() is zero-based, so you may
actually want add one to the resulting number:

  s = "Guido"
  for num, line in enumerate(open("file.txt")):
    if s in line:
      print "Found %s on line %i" % (s, num + 1)
      break # optionally stop looking

Or one could use a tool made for the job:

  grep -n Guido file.txt

or if you only want the first match:

  sed -n '/Guido/{=;p;q}' file.txt


More information about the Python-list mailing list