Get Line Number of certain phrase in file Python

PythonFile

Python Problem Overview


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.

Python Solutions


Solution 1 - Python

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

Solution 2 - Python

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

EDIT 1.5 years later (after seeing it get another upvote): I'm leaving this as is; but if I was writing today would write something closer to Ash/suzanshakya's solution:

def line_num_for_phrase_in_file(phrase='the dog barked', filename='file.txt')
    with open(filename,'r') as f:
        for (i, line) in enumerate(f):
            if phrase in line:
                return i
    return -1
  • Using with to open files is the pythonic idiom -- it ensures the file will be properly closed when the block using the file ends.
  • Iterating through a file using for line in f is much better than for line in f.readlines(). The former is pythonic (e.g., would work if f is any generic iterable; not necessarily a file object that implements readlines), and more efficient f.readlines() creates an list with the entire file in memory and then iterates through it. * if search_phrase in line is more pythonic than if line.find(search_phrase) >= 0, as it doesn't require line to implement find, reads more easily to see what's intended, and isn't easily screwed up (e.g., if line.find(search_phrase) and if line.find(search_phrase) > 0 both will not work for all cases as find returns the index of the first match or -1).
  • Its simpler/cleaner to wrap an iterated item in enumerate like for i, line in enumerate(f) than to initialize line_num = 0 before the loop and then manually increment in the loop. (Though arguably, this is more difficult to read for people unfamiliar with enumerate.)

See code like pythonista

Solution 3 - Python

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

Solution 4 - Python

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)

Solution 5 - Python

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.

Solution 6 - Python

listStr = open("file_name","mode")

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

Solution 7 - Python

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)

Solution 8 - Python

for n,line in enumerate(open("file")):
    if "pattern" in line: print n+1

Solution 9 - Python

Here's what I've found to work:

f_rd = open(path, 'r')
file_lines = f_rd.readlines()
f_rd.close()

matches = [line for line in file_lines if "chars of Interest" in line]
index = file_lines.index(matches[0])

Solution 10 - Python

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

Solution 11 - Python

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionZac BrownView Question on Stackoverflow
Solution 1 - PythonSachaView Answer on Stackoverflow
Solution 2 - Pythondr jimbobView Answer on Stackoverflow
Solution 3 - PythonsuzanshakyaView Answer on Stackoverflow
Solution 4 - PythonAmarjeet RanasinghView Answer on Stackoverflow
Solution 5 - PythonslezicaView Answer on Stackoverflow
Solution 6 - PythonM. kavin babuView Answer on Stackoverflow
Solution 7 - PythonAlon BaradView Answer on Stackoverflow
Solution 8 - Pythonghostdog74View Answer on Stackoverflow
Solution 9 - PythonOnkar RautView Answer on Stackoverflow
Solution 10 - Pythonoptimus_primeView Answer on Stackoverflow
Solution 11 - PythonKumaTeaView Answer on Stackoverflow