The [project outline][1]:


  [1]: https://automatetheboringstuff.com/2e/chapter9/

> 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_inp = input("What do you want to find? (Enter nothing to search another path)\n")
                rx_obj = re.compile(user_inp)
                if user_inp == "":
                    break
                else:
                    for filename in all_files:
                        text_file = open(Path(user_path) / filename)
                        for line in text_file.readlines():
                            mo = rx_obj.findall(line)
                            for match in mo:
                                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.