Files

22 lines
700 B
Python
Raw Permalink Normal View History

2017-06-20 08:29:48 +08:00
#! python3
'''
regex_search.py - opens all .txt files in a folder and searches for any line
that matches a user-supplied regular expression. The results
should be printed to the screen.
'''
import os
2017-06-20 11:14:34 +08:00
import re
2017-06-20 08:29:48 +08:00
target_folder = input("Enter the target foulder:\n")
os.chdir(target_folder)
target_files = os.listdir(target_folder)
target_files = [target for target in target_files if target.endswith('.txt')]
2017-06-20 11:14:34 +08:00
regex = re.compile(input('Enter the regular expression:\n'))
for file_name in target_files:
file = open(file_name)
for line in file.readlines():
words = regex.findall(line)
if words:
print(file_name + ": " + str(words))