Limited Search for File

bumsfeld 0 Tallied Votes 209 Views Share

Search for a file given its name and the starting search directory. The search is limited to a set depth of subdirectories. Python makes this easy to do.

# search for a filename in a given folder and its subfolders,
# but limit the depth of subdirectories to search in
# tested with Python24  by  HAB

import os

def limited_walk(folder, limit, n = 0):
    """generator similar to os.walk(), but with limited subdirectory depth"""
    if n > limit:
        return
    for file in os.listdir(folder):
        file_path = os.path.join(folder, file)
        if os.path.isdir(file_path):
            for item in limited_walk(file_path, limit, n + 1):
                yield item
        else:
            yield file_path

# file to search for ...
fname = "quiz2.py"
# folder to start search ...
folder = r"C:\Python24\Atest"

# search 1 subdirectory deep
# change the depth as needed
for filename in limited_walk(folder, 1):
    # make search case insensitive
    if os.path.basename(filename).lower() == fname.lower():
        result = filename
        break
    else:
        result = None

if result:
    print "File found -->", result
else:
    print "File %s not found" % fname