List files in a directory with Python

Choose a one-level listing, a glob pattern, or recursive traversal, and explicitly filter regular files and handle ordering, links, and filesystem changes.

Best practices
Python programming and application logging

Use os.listdir() or Path.iterdir() for one directory level. Use globbing for a name pattern and os.walk() or Path.rglob() for recursive discovery. A directory listing can contain directories and other entries as well as regular files.

List immediate names

import os

path = "/path/to/dir"
for name in os.listdir(path):
    print(name)

Replace the path with an existing directory. listdir() returns entry names without the parent prefix. To select regular files, following symlinks to their targets:

files = [
    name for name in os.listdir(path)
    if os.path.isfile(os.path.join(path, name))
]

The listing and the check happen at different times; entries can disappear or change between operations.

Use pathlib and patterns

from pathlib import Path

folder = Path("/path/to/dir")
for entry in folder.iterdir():
    if entry.is_file():
        print(entry.name)

for entry in folder.glob("*.log"):
    if entry.is_file():
        print(entry)

for entry in folder.rglob("*.log"):
    if entry.is_file():
        print(entry)

A matching suffix alone does not prove the entry is a file; a directory can also be named archive.log. Path.glob("**/*.py") provides recursive matching similar to rglob("*.py"). Symlink recursion and error handling have version-specific options, so check the supported Python version when those details matter.

Walk a directory tree

import os

def report_error(error):
    raise error

for directory, subdirectories, filenames in os.walk(
    "/path/to/dir", onerror=report_error, followlinks=False
):
    for name in filenames:
        print(os.path.join(directory, name))

By default, os.walk() does not descend into symlinked directories. Enabling link traversal can create cycles, and walk does not track visited directories for you. The filenames list contains nondirectory entries, which can include symlinks or special files; add a type check if you need only regular files.

Read metadata with scandir

import os

with os.scandir("/path/to/dir") as entries:
    for entry in entries:
        if entry.is_file(follow_symlinks=False):
            info = entry.stat(follow_symlinks=False)
            print(entry.name, info.st_size, info.st_mtime)

This example excludes symlinks and reports size in bytes and a modification timestamp. scandir() can reuse directory-entry metadata where the operating system provides it, avoiding some extra calls. Filesystem changes can still make later reads fail.

FAQ

Is the order stable? Do not depend on filesystem enumeration order. Use sorted() for a predictable listing and explicitly sort walk's directory/file lists if recursive order matters.

What happens on permission errors? APIs and Python releases differ in which errors are raised or suppressed. For walk, onerror makes failures explicit. Avoid claiming a complete inventory if inaccessible directories were silently skipped.

References

Get a tailored plan

Contact us

Join the community

Scan with WeChat
to join the community

Try Guance

Start online and pay only for what you use.

Get started

Choose a Guance plan

Code hosting