ABSP, Ch 8, Practice Project #3

My solution to the Practice Project #3 in Chapter 8 of the excellent book “Automate the Boring Stuff with Python” (ABSP)

#! usr/bin/env python3
# by lorenzo - 18/08/2017
# regex search - program that opens all .txt files in a folder
#                and searches for any line that matches a user-supplied regex.
#                The results are printed to the screen

import re, os

def addToList(list1, list2):
    for i in range(len(list1)):

print('Enter a regular expression:')
myRegex = input()
thisRegex = re.compile(myRegex)

location = ''
print('Enter directory you want to search in:')
location = input()
myFiles = os.listdir(location)
myList = []
for myFile in myFiles:
    if myFile.endswith('.txt'):
        thisFile = open(myFile, 'r')
        myContent = thisFile.read()
        listToAdd = thisRegex.findall(myContent)
        addToList(listToAdd, myList)

for match in myList:
    print(match, sep = ' ')

Comments about the code are welcome.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s