python – How to use glob() to find files recursively?

python – How to use glob() to find files recursively?


Use pathlib.Path.rglob from the the pathlib module, which was introduced in Python 3.5.

from pathlib import Path

for path in Path(src).rglob(*.c):

If you dont want to use pathlib, use can use glob.glob(**/*.c), but dont forget to pass in the recursive keyword parameter and it will use inordinate amount of time on large directories.

For cases where matching files beginning with a dot (.); like files in the current directory or hidden files on Unix based system, use the os.walk solution below.


For older Python versions, use os.walk to recursively walk a directory and fnmatch.filter to match against a simple expression:

import fnmatch
import os

matches = []
for root, dirnames, filenames in os.walk(src):
    for filename in fnmatch.filter(filenames, *.c):
        matches.append(os.path.join(root, filename))

Similar to other solutions, but using fnmatch.fnmatch instead of glob, since os.walk already listed the filenames:

import os, fnmatch

def find_files(directory, pattern):
    for root, dirs, files in os.walk(directory):
        for basename in files:
            if fnmatch.fnmatch(basename, pattern):
                filename = os.path.join(root, basename)
                yield filename

for filename in find_files(src, *.c):
    print Found C source:, filename

Also, using a generator alows you to process each file as it is found, instead of finding all the files and then processing them.

python – How to use glob() to find files recursively?

For python >= 3.5 you can use **, recursive=True :

import glob
for f in glob.glob(/path/**/*.c, recursive=True):

If recursive is True, the pattern ** will match any files and zero
or more directories and subdirectories
. If the pattern is followed by
an os.sep, only directories and subdirectories match.

Python 3.6 Demo

Leave a Reply

Your email address will not be published. Required fields are marked *