How to use Glob() function to find files recursively in Python?

Published on Aug. 22, 2023, 12:15 p.m.

To use the glob() function to find files recursively in Python, you can use the ** wildcard character in the search pattern. Here’s an example:

import glob

# finds all .txt files recursively in a directory
files = glob.glob('/path/to/directory/**/*.txt', recursive=True)

# prints the list of matching file names
print(files)

In this example, we import the glob module and use its glob() function to search for all files with the .txt extension in the directory /path/to/directory, including all subdirectories. We pass the recursive=True parameter to search recursively. The function returns a list of matching file names, which we print to the console.

Make sure you have Python 3.5 or higher to use the ** character to search recursively with glob().

Tags: