[Python] How can I optimize my depth-first-search algorithm for searching files in my disk...

Discussão em 'Python' iniciado por Stack, Agosto 16, 2025.

  1. Stack

    Stack Membro Participativo

    This small script finds files and folders by recursively parsing through directory structures and returning the paths they are stored. This was done for the sole purpose of finding a folder on my D drive. While the code functions effectively, it's run time is pretty slow. I explored the os.walk alternative but it seems some seconds slower than my manual recursive code. I would appreciate your feedback on how I can optimize it to run faster. Thank you.

    import os
    import re

    rootPath = 'C:\\'

    search = input("Enter file you are looking for ")
    escaped = re.escape(search)
    pattern = re.compile(escaped.replace(r"\ ", r"\s*"), re.IGNORECASE)
    def recursiveDirFinder(root,target):
    dirs = os.listdir(root)
    for dir in dirs:
    try:
    path = os.path.join(root,f"{dir}\\")
    if target.search(dir):
    print(path)
    else:
    if os.path.isdir(path):
    recursiveDirFinder(path,target)
    else:
    continue
    except UnicodeEncodeError:
    #print(f"Error processing {dir}")
    continue
    except PermissionError:
    #print(f"{dir} cannot be accessed")
    continue
    except OSError:
    continue

    recursiveDirFinder(rootPath,pattern)

    Continue reading...

Compartilhe esta Página