pythonfile

Get Line Number of certain phrase in text file


I need to get the line number of a phrase in a text file. The phrase could be:

the dog barked

I need to open the file, search it for that phrase and print the line number.

I'm using Python 2.6 on Windows XP


This Is What I Have:

o = open("C:/file.txt")
j = o.read()
if "the dog barked" in j:
     print "Found It"
else:
     print "Couldn't Find It"

This is not homework, it is part of a project I am working on. I don't even have a clue how to get the line number.


Solution

  • lookup = 'the dog barked'
    
    with open(filename) as myFile:
        for num, line in enumerate(myFile, 1):
            if lookup in line:
                print 'found at line:', num