Home >Backend Development >Python Tutorial >What's the Best Way to Recursively Find Files in Python?
Finding Files Recursively with Different Methods
When searching for files recursively in a directory structure, glob() may not be the most efficient or comprehensive approach. This article explores alternative methods to achieve recursive file listing:
pathlib.Path().rglob()
The pathlib module introduces pathlib.Path().rglob(), which recursively searches for matching files. Example:
from pathlib import Path for path in Path('src').rglob('*.c'): print(path.name)
glob.glob() with recursive=True
For Python versions prior to 3.5, glob.glob() offers a recursive option. Example:
from glob import glob for filename in glob('src/**/*.c', recursive=True): print(filename)
os.walk()
For older Python versions, os.walk() combined with fnmatch.filter() provides a recursive search. Example:
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))
The os.walk() method iterates through all subdirectories, while fnmatch.filter() applies a simple pattern matching. This approach may be more efficient for large directories due to the lower overhead compared to pathlib.
The above is the detailed content of What's the Best Way to Recursively Find Files in Python?. For more information, please follow other related articles on the PHP Chinese website!