Home >Backend Development >Python Tutorial >How Can I Recursively List All Files in a Directory Using Python?

How Can I Recursively List All Files in a Directory Using Python?

Barbara Streisand
Barbara StreisandOriginal
2024-12-19 17:21:10872browse

How Can I Recursively List All Files in a Directory Using Python?

Iterating over Files Recursively

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!

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