views:

70

answers:

5

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.

+1  A: 

Open your file, and then do something like...

for line in f:
    nlines += 1
    if (line.find(phrase) >= 0):
        print "Its here.", nlines

There are numerous ways of reading lines from files in Python, but the for line in f technique is more efficient than most.

Santiago Lezica
that's wrong and embarrassing.
SilentGhost
Wrong? Where? ...? If it's the > instead of >=, I just fixed it, you are right, and ... you could've just pointed that out instead of saying the answer was wrong and embarrasing.
Santiago Lezica
@santi: embarrassment was writing c code in python. See Sacha's answer
SilentGhost
Yeah, I was unable to get it working. Thanks for posting though.
Zachary Brown
Not wrong, just not Pythonic. I'm quite amused by the extra parentheses in the `if` statement.
Mark Ransom
@silent come oooon, the question wasn't "what's the most pythonesque way of finding a string in file", maan. Zachary seemed to know little about python, so I wrote a more language-agnostic answer. He is right, tough, Zach: for a better-looking solution, see Sacha's.
Santiago Lezica
@mark: of course it's not wrong! *any more*. Santiago seems to have a thing for parentheses.
SilentGhost
@Santiago: on opposite! OP says he's a *very strong Python programmer*
SilentGhost
They can hear you guys, they are a few lines above these comments. Leave my parentheses alone. They have feelings, you know.
Santiago Lezica
A: 
f = open('some_file.txt','r')
line_num = 0
search_phrase = "the dog barked"
for line in f.readlines():
    line_num += 1
    if line.find(search_phrase) >= 0:
        print line_num
jimbob
This is similar to Santiago's solution; except it should be >= 0, as if its at the beginning of the line, find will return 0 if the phrase is present. (If its not there it will be -1).
jimbob
-1 to get it back to 0. Using readlines is rarely a good idea, just iterate the file.
delnan
+5  A: 
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
Sacha
Thank you for posting *the right way(tm)* to do it (well, except that line counting starts at 0 - ok for programmers but propably not for non-techies). +1
delnan
This is what worked. Now, just a question... do you know how to read a specific line number in a text file?
Zachary Brown
In python 2.6 and later, I think, `enumerate()` takes an argument of the number to start counting at, e.g. `enumerate(myFile, 1)`.
hughdbrown
Thanks for the comments, I edited it for python 2.6 (print) and the line starting at 1.
Sacha
You can check this post for the opening the file at a specific line: http://stackoverflow.com/questions/620367/python-how-to-jump-to-a-particular-line-in-a-huge-text-file
Sacha
+1  A: 
def get_line_number(phrase, file_name):
    with open(file_name) as f:
        for i, line in enumerate(f, 1):
            if phrase in line:
                return i
        return 0
suzanshakya
I would use `return None` rather than `return 0` but this is good.
Mark Ransom
I used `return 0` to make the return type of `get_line_number` integer. Why do you think `return None` is better ?
suzanshakya
`None` makes it clear that the phrase wasn't found, while `0` is just a convention. Also it ensures that if the result isn't checked by the caller, the program will likely fail in a spectacular way when the bug is tripped, making debugging easier.
Mark Ransom
Thanks Mark for the explanation.
suzanshakya
A: 
for n,line in enumerate(open("file")):
    if "pattern" in line: print n+1
ghostdog74