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

](https://stackoverflow.com/users/169175/ben-gartner)

This is what I have:

glob(os.path.join('src','*.c'))

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

glob(os.path.join('src','*.c'))
glob(os.path.join('src','*','*.c'))
glob(os.path.join('src','*','*','*.c'))
glob(os.path.join('src','*','*','*','*.c'))

But this is obviously limited and clunky.

Answer by Johan Dahlin

pathlib.Path.rglob

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'):
    print(path.name)

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.

os.walk

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 💬