Get Line Number of certain phrase in file 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)
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 thanfor line in f.readlines()
. The former is pythonic (e.g., would work iff
is any generic iterable; not necessarily a file object that implementsreadlines
), and more efficientf.readlines()
creates an list with the entire file in memory and then iterates through it. *if search_phrase in line
is more pythonic thanif line.find(search_phrase) >= 0
, as it doesn't requireline
to implementfind
, reads more easily to see what's intended, and isn't easily screwed up (e.g.,if line.find(search_phrase)
andif 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
likefor i, line in enumerate(f)
than to initializeline_num = 0
before the loop and then manually increment in the loop. (Though arguably, this is more difficult to read for people unfamiliar withenumerate
.)
See code like pythonista
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
print get_line_number("the dog barked", "C:/file.txt") # python2
#print(get_line_number("the dog barked", "C:/file.txt")) # python3
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