|
| 1 | +import os |
| 2 | +import uuid |
| 3 | + |
| 4 | +# Initialize a list to store files containing the keyword |
| 5 | +contains = [] |
| 6 | + |
| 7 | +# Generate a unique identifier for this search session (not currently used) |
| 8 | +id_ = uuid.uuid4() |
| 9 | + |
| 10 | +# List of file extensions to search within |
| 11 | +extensions = [".txt", ".docx", ".pdf"] |
| 12 | + |
| 13 | +def change_direct(): |
| 14 | + # Prompt the user to enter the directory path |
| 15 | + path = input("Enter path: ") |
| 16 | + # Prompt the user to enter the keyword or phrase to search for |
| 17 | + keyword = input("Keyword/Phrase: ") |
| 18 | + # Start searching the specified folder |
| 19 | + search_folder(path, keyword) |
| 20 | + |
| 21 | +def search_folder(path, keyword): |
| 22 | + global contains # Declare the global variable to store found files |
| 23 | + # Check if the given path is a directory |
| 24 | + if os.path.isdir(path): |
| 25 | + # List all files and directories in the specified path |
| 26 | + files = os.listdir(path) |
| 27 | + # Iterate over each file in the directory |
| 28 | + for file in files: |
| 29 | + # Construct the full path to the file or directory |
| 30 | + full_path = os.path.join(path, file) |
| 31 | + |
| 32 | + # If the current path is a directory, recursively search inside it |
| 33 | + if os.path.isdir(full_path): |
| 34 | + search_folder(full_path, keyword) |
| 35 | + else: |
| 36 | + # Get the file extension and convert it to lowercase |
| 37 | + filetype = os.path.splitext(file)[-1].lower() |
| 38 | + # Check if the file type is in the allowed extensions |
| 39 | + if filetype in extensions: |
| 40 | + try: |
| 41 | + # Open the file and read its content |
| 42 | + with open(full_path, 'r', encoding='utf-8', errors='ignore') as file_: |
| 43 | + # Check if the keyword is found in the file content |
| 44 | + if keyword in file_.read(): |
| 45 | + contains.append(file) # Add the file to the list of found files |
| 46 | + print(keyword, "found in", file) # Print the result |
| 47 | + except Exception as e: |
| 48 | + # Print any errors encountered while reading the file |
| 49 | + print(f"Error reading {full_path}: {e}") |
| 50 | + else: |
| 51 | + # Print an error message if the provided path is not a directory |
| 52 | + print(f"{path} is not a directory.") |
| 53 | + |
| 54 | +# Start the process by calling the change_direct function |
| 55 | +change_direct() |
0 commit comments