Home >Backend Development >Python Tutorial >How Can I Recursively List All Files in a Directory Using Python?
Recursively traversing directory structures to list all files is a common programming need. In this context, let's explore how to accomplish this efficiently in Python.
One approach is using the pathlib.Path().rglob() method, introduced in Python 3.5. It provides a convenient way to identify all files matching a specific pattern in a directory and its subdirectories:
from pathlib import Path for path in Path('src').rglob('*.c'): print(path.name)
If you prefer using the glob module, you can leverage its glob() function with the recursive=True argument:
from glob import glob for filename in glob('src/**/*.c', recursive=True): print(filename)
Another option, compatible with older Python versions, involves using os.walk() for recursive traversal and fnmatch.filter() for pattern matching:
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() technique may prove faster in scenarios with extensive file counts due to the lower overhead associated with the pathlib module.
Whichever approach you choose, these methods will effectively assist you in recursively identifying and listing files within a specified directory and its subfolders.
The above is the detailed content of How Can I Recursively List All Files in a Directory Using Python?. For more information, please follow other related articles on the PHP Chinese website!