[Solved] Open and read all text Files in your directory and filter them using regular expression, python


This is using glob rather than listdir, but this might be a possible method. No regular expressions involved here either though.

import glob

folder_path = "C:\Temp"
file_pattern = "\*.txt"
search_string = "hello"

match_list = []

folder_contents = glob.glob(folder_path + file_pattern)

for file in folder_contents:
    print("Checking", file)
    read_file = open(file, 'rt').read()

    if search_string in read_file:
        match_list.append(file)

print("Files containing search string")
for file in match_list:
    print(file)

1

solved Open and read all text Files in your directory and filter them using regular expression, python