How to use glob() to find files recursively?

How to use glob() to find files recursively?

  1. Question by [Ben Gartner
  2. Answer by Johan Dahlin
  3. Answer by Milovan Tomašević

Question by [Ben Gartner


This is what I have:


but I want to search the subfolders of src. Something like this would work:


But this is obviously limited and clunky.

Answer by Johan Dahlin


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 don’t want to use pathlib, use can use glob.glob('**/*.c'), but don’t 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))

Answer by Milovan Tomašević

import os, glob

for each in glob.glob('path/**/*.c', recursive=True):
    print(f'Name with path: {each} \nName without path: {os.path.basename(each)}')
- `glob.glob('*.c')                    `:matches all files ending in `.c` in current directory
- `glob.glob('*/*.c')                  `:same as 1
- `glob.glob('**/*.c')                 `:matches all files ending in `.c` in the immediate subdirectories only, but not in the current directory
- `glob.glob('*.c',recursive=True)     `:same as 1
- `glob.glob('*/*.c',recursive=True)   `:same as 3
- `glob.glob('**/*.c',recursive=True)  `:matches all files ending in `.c` in the current directory and in all subdirectories

Improve this page: 

Share on:      

Comments 💬