Finding files with Python

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

Lasă un răspuns

Completează mai jos detaliile tale sau dă clic pe un icon pentru a te autentifica:

Logo WordPress.com

Comentezi folosind contul tău WordPress.com. Dezautentificare /  Schimbă )

Fotografie Google

Comentezi folosind contul tău Google. Dezautentificare /  Schimbă )

Poză Twitter

Comentezi folosind contul tău Twitter. Dezautentificare /  Schimbă )

Fotografie Facebook

Comentezi folosind contul tău Facebook. Dezautentificare /  Schimbă )

Conectare la %s

Acest site folosește Akismet pentru a reduce spamul. Află cum sunt procesate datele comentariilor tale.