Home > Backend Development > Python Tutorial > What's the Best Way to Recursively Find Files in Python?

What's the Best Way to Recursively Find Files in Python?

Patricia Arquette
Release: 2024-12-19 05:34:09
Original
499 people have browsed it

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)
Copy after login

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)
Copy after login

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))
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template