Home >Backend Development >Python Tutorial >How Can I Recursively Find Files in Python Using `pathlib`, `glob`, and `os.walk`?

How Can I Recursively Find Files in Python Using `pathlib`, `glob`, and `os.walk`?

DDD
DDDOriginal
2024-12-11 20:16:15312browse

How Can I Recursively Find Files in Python Using `pathlib`, `glob`, and `os.walk`?

Finding Files Recursively: Exploring pathlib.rglob(), glob.glob(), and os.walk()

When dealing with complex directory structures, it becomes essential to locate files recursively. This task can be simplified using various Python modules and methods.

One approach is to utilize pathlib.Path().rglob() introduced in Python 3.5. It allows for straightforward recursive file searching:

from pathlib import Path

for path in Path('src').rglob('*.c'):
    print(path.name)

Alternatively, glob.glob() provides another option for recursive file listing:

from glob import glob

for filename in glob('src/**/*.c', recursive=True):
    print(filename)

This method also supports matching files beginning with a dot (.).

For older Python versions or when speed is crucial, os.walk() offers a reliable solution:

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))

By choosing the appropriate method based on your Python version and performance requirements, you can effectively list files recursively within directories and subdirectories.

The above is the detailed content of How Can I Recursively Find Files in Python Using `pathlib`, `glob`, and `os.walk`?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn