The project outline:
Write a program that 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.
My solution:
import os, re
from pathlib import Path
while True:
user_path = input("Enter a path to search: ")
if user_path == "":
print("Please enter a valid path.")
elif Path(user_path).exists() != True:
print("This path does not exist.")
else:
while True:
all_files = os.listdir(user_path)
matches = []
lines = []
user_input = input("What do you want to find? (Enter nothing to search another path)\n")
regex_object = re.compile(user_input)
if user_input == "":
break
else:
for filename in all_files:
if filename.endswith(".txt") != True:
continue
text_file = open(Path(user_path) / filename)
for line in text_file.readlines():
match_object = regex_object.findall(line)
for match in match_object:
matches.append(match)
lines.append(line)
text_file.close()
if matches == []:
print("No matches found")
else:
print(matches)
print(lines)
Thanks in advance for the critique.