Skip to content
Advertisement

How to use glob() to find files recursively?

This is what I have:

JavaScript

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

JavaScript

But this is obviously limited and clunky.

Advertisement

Answer

pathlib.Path.rglob

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

JavaScript

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:

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement