To search a file using grep-like functionality in Python, you can read the file and then use regular expressions provided by the “re” module to search for patterns. It will globally search for a regular expression and print the line if a match is found.
GREP stands for “Globally search for Regular Expression and Print matching lines”. It is a command-line utility in Unix-like systems for searching plain-text data sets for lines matching a regular expression.
Here is the step-by-step guide:
Step 1: Open a file in write mode.
To open a file, use the open() method.
file = open("data.txt", "w")
Step 2: Write some content in that file.
You can write the content inside the file using the file.write() function. Then close the file.
file.write("One Up\nTwo Friends\nThree Musketeers")
file.close()
Here is the written data.txt file:
Step 3: Define a pattern you want to search for in the file.
pattern = "Friends"
We want to search for the “Friends” word in the file.
Step 4: Open a file in reading mode.
We want to search for a keyword, and to do that, we open that file using the open() function in read mode.
file = open("data.txt", "r")
Step 5: Using a for loop to read line-by-line
To match a string against a regular expression, use the re.search() method.
If it finds a match using a regular expression, then we will print the whole line.
For example, we are searching for the word ‘Friends,‘ and if it is found, it will print the whole line: ‘Two Friends.‘
for line in file:
if re.search(pattern, line):
print(line)
Here is the complete code:
import re
file = open("data.txt", "w")
file.write("One Up\nTwo Friends\nThree Musketeers")
file.close()
pattern = "Friends"
file = open("data.txt", "r")
for word in file:
if re.search(pattern, word):
print(word)
# Output: Two Friends
Output
That’s it.


