Find Specific Words in Text File and Print the Line Using Python

How to search for word in text file and print the entire line with Python?

You just do a non necessary for loop, try this:

with open("text.txt") as openfile:
for line in openfile:
if "Hello" in line:

Find specific words in text file and print the line using Python

def my_function():

with open("exampleValues",'r') as f, open('output.txt','w') as fw:
text =
result_string = ''

words = ["makan", "Rina", "mahal"]
text2 = text.split(".")
for itemIndex in range(len(text2)):
for word in words:
if word in text2[itemIndex]:
if text2[itemIndex][0] ==' ':
result_string += text2[itemIndex][1:]+'. '
result_string += text2[itemIndex]


If this useful. Don't forget vote me. Thanks.

How to search a text file for lines that contain a specific word, then create a new file with the "found" lines

search_word = 'your search word here'
with open('data.txt') as file: # opens it, then closes it automatically at the end of the with block
lines = [line for line in'\n') if search_word in line]

with open('output.txt', 'w+') as output_file: # 'w+' specifies it can be written to and created

Now we can break down lines = [line for line in'\n') if search_word in line] returns a string of the whole file

.split('\n') turns the string into a list, breaking it at every newline ('\n' is a newline)

if search_word in line so it only adds the lines with the words

'\n'.join(lines) puts the elected lines back together, then writes it to the file with write

Python: search for words in a text file and print line with line number

You are reading the file using which returns a string but you are expecting a list. Use file.readlines() instead. As an aside, it is better use open/close files using the with statement.


GrabdirectoryFile = open(args.input,"r",encoding='UTF8')                    
directoryFile =


GrabdirectoryFile = open(args.input,"r",encoding='UTF8')                    
directoryFile = GrabdirectoryFile.readlines()

Using a with statement is better:

with open(args.input,"r",encoding='UTF8') as GrabdirectoryFile:
directoryFile = GrabdirectoryFile.readlines()

How to find a word in a text file and print another that is in the next line in Python

You can search each line, then move to the next line, like so:

with open('text.txt','r') as f:
for line in f:
phrase = 'bye'
if phrase in line: #if the phrase is present
next(f) #move to next line

You can do whatever you want with the lines following this; if you're trying to find a number, you could use .isdigit() assuming the line only contains numbers.

A possible alternate solution is to use regular expressions:

import re

def hasNumber(string):
return bool('\d', string)) #returns true/false

with open('text.txt','r') as f:
for line in f:
if re.match('bye',line): #if it contains the word "bye"
newline = next(f) #declare the next line
if hasNumber(newline): #if that line contains any numbers
number = re.compile(r'\d') #find those numbers
print(''.join(number.findall(newline)[:])) #print those numbers

The re.match function returns true if the second variable matches the first (though this isn't strictly true, as it only acts this way with conditionals).

How to search for word in text file and print part of line with Python?

Here's one way - split each line by spaces, then search each part for "color=":

with open("textfile.txt") as openfile:
for line in openfile:
for part in line.split():
if "color=" in part:
print part

Extract lines containing specific words

You can write a simple parser with a flag. In summary, when you reach a line with AA and the word, set the flag True to keep the following fields of interest, until you reach a block end in which case you reset the flag.

word = 'Homo sapiens'

with open(input_file, 'r') as txtin, open(output_file, 'w') as txtout:
keep = False
for line in txtin:
if keep and line.startswith(('DR', 'FT', '//')):
if line.startswith('//'):
keep = False # reset the flag on record end
elif line.startswith('AA') and word in line:
keep = True


DR   ac
FT ae
DR cc
FT ce

NB. This requires AA to be before the fields to save. If not, you have to parse block by block (keeping the data in memory) with a similar logic

Related Topics

Leave a reply