How to Search a File with grep in Python

To search a file using grep in Python, import the re package, open the file and iterate over each line with a for loop. On each iteration call the re.search() function and pass the RegEx expression as the first argument and the line of data as the second.

 

re.search() Syntax

re.search(expression, data)

 

re.search() returns a truthy object when a match is found and None if not.

 

Python grep Example

To demonstrate this, let's open a .txt file and search for any lines containing the word "of".  The re.search() function will be placed in an if statement so we can determine whether to do something with the line if a match is found.

 

file.txt
Some content.
Another line of content.
import re

file = open('file.txt', 'r')

for l in file:
   if re.search('of', l):
       print(l)

file.close()
Another line of content.