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_inpuser_input = input("What do you want to find? (Enter nothing to search another path)\n")
rx_objregex_object = re.compile(user_inpuser_input)
if user_inpuser_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():
momatch_object = rx_objregex_object.findall(line)
for match in momatch_object:
matches.append(match)
lines.append(line)
text_file.close()
if matches == []:
print("No matches found")
else:
print(matches)
print(lines)
I feel like I've probably overcomplicated things...
Thanks in advance for the critique.
Edit: This only works when given a folder with only .txt files.