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)): list2.append(list1[i]) print('Enter a regular expression:') myRegex = input() thisRegex = re.compile(myRegex) location = '' print('Enter directory you want to search in:') location = input() os.chdir(location) myFiles = os.listdir(location) myList =  for myFile in myFiles: if myFile.endswith('.txt'): thisFile = open(myFile, 'r') myContent = thisFile.read() thisFile.close() listToAdd = thisRegex.findall(myContent) addToList(listToAdd, myList) for match in myList: print(match, sep = ' ')
Comments about the code are welcome.