Apps Artificial Intelligence CSS DevOps Go JavaScript Laravel Linux MongoDB MySQL PHP Python Rust Svelte Vue

How to List Files in a Directory with Python

1 min read .
How to List Files in a Directory with Python

Listing files in a directory is a common Python task for automation, data processing, uploads, and filesystem utilities. The standard library provides several good approaches.

1. os.listdir()

os.listdir() returns names for both files and subdirectories, so filter the results when you need only regular files:

import os

def list_files(directory):
    try:
        entries = os.listdir(directory)
        return [
            name
            for name in entries
            if os.path.isfile(os.path.join(directory, name))
        ]
    except FileNotFoundError:
        return []

2. os.scandir()

os.scandir() returns DirEntry objects that can expose file-type information efficiently:

import os

def list_files(directory):
    try:
        with os.scandir(directory) as entries:
            return [entry.name for entry in entries if entry.is_file()]
    except FileNotFoundError:
        return []

This is a strong choice when iterating large directories.

3. pathlib.Path

For modern Python code, pathlib often produces the clearest filesystem operations:

from pathlib import Path

def list_files(directory):
    path = Path(directory)
    return [item.name for item in path.iterdir() if item.is_file()]

Path.iterdir() raises FileNotFoundError if the directory does not exist, so catch that exception if a missing path is an expected condition.

4. Filter by Extension

With pathlib, glob patterns are concise:

from pathlib import Path

csv_files = list(Path("data").glob("*.csv"))

For recursive matching:

csv_files = list(Path("data").rglob("*.csv"))

5. Return Full Paths When Useful

Returning only .name loses the parent directory. If downstream code needs to open or move the files, keeping Path objects is often better:

files = [item for item in Path("data").iterdir() if item.is_file()]

for file_path in files:
    print(file_path)

Conclusion

Use os.listdir() for simple legacy-style code, os.scandir() when directory-entry efficiency matters, and pathlib.Path for readable modern filesystem code. Decide whether callers need filenames or complete paths before choosing the returned representation.

Related Posts

chevron-up