How do I search a text file for a key-phrase or keyword and then print the line that key-phrase or keyword is in?
The find(query) method is built-in to standard python. Just call the method on the string object to search for a string, like so: obj. find(“search”). The find() method searches for a query string and returns the character position if found.
searchfile = open("file.txt", "r")
for line in searchfile:
if "searchphrase" in line: print line
searchfile.close()
To print out multiple lines (in a simple way)
f = open("file.txt", "r")
searchlines = f.readlines()
f.close()
for i, line in enumerate(searchlines):
if "searchphrase" in line:
for l in searchlines[i:i+3]: print l,
print
The comma in print l,
prevents extra spaces from appearing in the output; the trailing print statement demarcates results from different lines.
Or better yet (stealing back from Mark Ransom):
with open("file.txt", "r") as f:
searchlines = f.readlines()
for i, line in enumerate(searchlines):
if "searchphrase" in line:
for l in searchlines[i:i+3]: print l,
print
with open('file.txt', 'r') as searchfile:
for line in searchfile:
if 'searchphrase' in line:
print line
With apologies to senderle who I blatantly copied.
Note the potential for an out-of-range index with "i+3". You could do something like:
with open("file.txt", "r") as f:
searchlines = f.readlines()
j=len(searchlines)-1
for i, line in enumerate(searchlines):
if "searchphrase" in line:
k=min(i+3,j)
for l in searchlines[i:k]: print l,
print
Edit: maybe not necessary. I just tested some examples. x[y] will give errors if y is out of range, but x[y:z] doesn't seem to give errors for out of range values of y and z.
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