Python grep: How to Search a File Using Grep in Python
Grep means to search a file using regular expression. You are searching for a specific pattern in the file, and if it is found, you perform some operations.
To search a file using grep in Python means it will globally search for a regular expression and print the line if it finds the match. Follow the below steps for Python grep.
- To open a file in write mode, use the open() method.
- Write some content using the file.write() function and close the file.
- Define a pattern which you want to find inside the file.
- Now, open the file in the read form.
- Use the for loop, and inside that, use the re.search() method to find the pattern and if it searches the match, then print the output.
Step 1: Open a file in write mode.
To open a file in Python, use the open() method.
file = open("data.txt", "w")
Step 2: Write some content in that file.
Then 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()
Step 3: Define a pattern you want to search in the file.
Define a pattern.
pattern = "Friends"
So we want to search Friends word in the file.
Step 4: Open a file in reading mode.
We want to search a keyword, and to do that, open that file using the open() function in read mode.
file = open("data.txt", "r")
Step 5: Use for loop to read line by line
To match a string against regular expression in Python, use the re.search() method. To work with regular expressions in R, import the re module at the head of the file.
If it finds a match using a regular expression, then we will print the whole line. For example, we are searching for Friends word, and if it finds, then it will print the whole line: Two Friends.
for line in file: if re.search(pattern, line): print(line)
So we are reading a file line by line, and if it finds any word against the pattern, it will print the complete line. See 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)
That’s it. We have searched a file using grep via a regular expression.
This is it for Python grep example.