Dragoș Iorgulescu



file_search

Just another entry in my Python-related scrapbook :). There are many occasions when having some code snippets related to file searches can prove useful.

Find for the first occurrence of a given filename in a given directory:

import os

def findFile(fileName, pathToSearch):
    for root, directories, files in os.walk(pathToSearch):
        if fileName in files:
            return os.path.join(root, fileName)

Find all files matching a given pattern and return a vector (list) with all entries (not that elegant yet, but it'll do for the moment):

import os
import fnmatch

def findFileAllMatches(patternToFind, pathToSearch):
    results = []
        for root, dirs, files in os.walk(pathToSearch):
            for name in files:
                if fnmatch.fnmatch(name, patternToFind):
                    result.append(os.path.join(root, name))

    return results