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
Release: 2024-12-19 17:21:10
Original
841 people have browsed it

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

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

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

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!

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