Python Basics: Script to find text in file

Using a for loop and regular expressions, we could pull out each line of a file that matches on a specific keyword. This is similar to doing a
tail [file] | grep “[some keyword]”

In this example below I assign a variable to open a file called server.log. Then I assign a variable called “pattern” to look for a keyword of ERROR. Finally, using a for loop, I iterate over the file line by line (where x is each line of the file) and filter for the pattern match with a if statement.

import re
infile = open('server.log','r')
pattern = re.compile("ERROR")
for x in infile:
    if pattern.match(x):
        print(x)

If the server.log contents was:
Log file text
more text
some log file stuff here
DEBUG: we have some debug text
INFO: ah we have some info text in the log
ERROR: We have an error!
some more text
ERROR: Another error!

Then the output will be:
ERROR: We have an error!

ERROR: Another error!

Creating a Function
This can be improved to make it a function like so:

import re

def find_word(word, file_name):
    infile = open(file_name,'r')
    pattern = re.compile(word)
    for x in infile:
        if pattern.match(x):
            print(x)

find_word("DEBUG","server.log")

Leave a Reply

Your email address will not be published. Required fields are marked *