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.
getline("Quotes. txt", number) #Create a new variable in order to grab the specific line, the variable #integer can be replaced by any integer of your choosing. print(lines) #This will print the line of your choosing. If you are completing this in python make sure you have both files (.
The most easiest way to count the number of lines, words, and characters in text file is to use the Linux command “wc” in terminal. The command “wc” basically means “word count” and with different optional parameters one can use it to count the number of lines, words, and characters in a text file.
read() print('Total words: ', len(file_contents. split())) print('total stops: ', file_contents. count('. '))
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
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
with
to open files is the pythonic idiom -- it ensures the file will be properly closed when the block using the file ends. 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). 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With