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

Ryan Ginstrom software at ginstrom.com
Tue Jan 8 11:29:11 CET 2008


> On Behalf Of Horacius ReX
> 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
>>>

Regards,
Ryan Ginstrom




More information about the Python-list mailing list