Get Line Number of certain phrase in file Python

Viewed 192775

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.

11 Answers

suzanshakya, I'm actually modifying your code, I think this will simplify the code, but make sure before running the code the file must be in the same directory of the console otherwise you'll get error.

lookup="The_String_You're_Searching"
file_name = open("file.txt")
for num, line in enumerate(file_name,1):
        if lookup in line:
            print(num)
listStr = open("file_name","mode")

if "search element" in listStr:
    print listStr.index("search element")  # This will gives you the line number

You can use list comprehension:

content = open("path/to/file.txt").readlines()

lookup = 'the dog barked'

lines = [line_num for line_num, line_content in enumerate(content) if lookup in line_content]

print(lines)

It's been a solid while since this was posted, but here's a nifty one-liner. Probably not worth the headache, but just for fun :)

from functools import reduce 
from pathlib import Path

my_lines       = Path('path_to_file').read_text().splitlines()       
found, linenum = reduce(lambda a, b: a if a[0] else (True, a[1]) if testid in b else (False, a[1]+1), [(False,0)] + my_lines)
            
print(my_lines[linenum]) if found else print(f"Couldn't find {my_str}")

Note that if there are two instances in the file, it wil

An one-liner solution:

l_num = open(file).read()[:open(file).read().index(phrase)].count('\n') + 1

and an IO safer version:

l_num = (h.close() or ((f := open(file, 'r', encoding='utf-8')).read()[:(f.close() or (g := open(file, 'r', encoding='utf-8')).read().index(phrase))].count('\n') + (g.close() or 1))) if phrase in (h := open(file, 'r', encoding='utf-8')).read() else None

Explain:

file = 'file.txt'
phrase = 'search phrase'
with open(file, 'r', encoding='utf-8') as f:
    text = f.read()
    if phrase in text:
        phrase_index = text.index(phrase)
        l_num = text[:phrase_index].count('\n') + 1  # Nth line has n-1 '\n's before
    else:
        l_num = None
Related