Answer the question
In order to leave comments, you need to log in
How to search for a keyword in a file of all lines where it is present?
I have a file with several lines in it.
I need to search for a keyword or phrase in a file to find all lines containing that word or that phrase.
I know that this is done through the re library
. There is re.findall(r'pattern', 'text to search')
You need to do this through the variable name. Well, for example, this is a variable var1 and var2. I need to replace quoted texts with variable names, but how?
And you also need to replace the 'text to search' with the name of the variable containing the path to the file in which you want to search. The file is text. You need to search throughout the file.
Hope you can help
Thanks in advance
Answer the question
In order to leave comments, you need to log in
Regular expressions are a very powerful tool, and your task is quite simple.
For your case, instead of re.findall, it is better to use a test for the occurrence of a substring using the in keyword.
with open(filename,"r") as myfile:
for line in myfile:
if var1 in line:
print(line)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question