Latest Code Tutorials

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.

Python grep

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.

  1. To open a file in write mode, use the open() method.
  2. Write some content using the file.write() function and close the file.
  3. Define a pattern which you want to find inside the file.
  4. Now, open the file in the read form.
  5. Use the for loop, and inside that, use the 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")

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 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, 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")

pattern = "Friends"

file = open("data.txt", "r")

for word in file:
    if, word):


Two Friends

That’s it. We have searched a file using grep via a regular expression.

This is it for Python grep example.

See also

Python re.sub()

Python re.replace()

Python regex

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.