Full Search for File

bumsfeld 0 Tallied Votes 149 Views Share

This Python code will search for given filename starting with given directory. It will also search all the subdirectories in the given directory. The search will end at the first hit.

# search for a filename in a given folder and all its subfolders
# tested with Python24  by  HAB

import os

def file_find(folder, fname):
    """search for a filename fname starting in folder"""
    for root, dirs, files in os.walk(folder):
        for file in files:
            # make search case insensitive
            if fname.lower() == file.lower():
                return os.path.join(root, fname)
    return None

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

result = file_find(folder, fname)

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