Skip to main content
2 of 3
added 67 characters in body
Javana
  • 451
  • 2
  • 6

Automate the Boring Stuff Chapter 9 - Regex Search

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_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.

Javana
  • 451
  • 2
  • 6