Skip to main content
Files

How to list files in a directory in Python

Quick answer

Path('.').iterdir() lists direct children. Path('.').rglob('*.py') walks the tree matching a pattern.

from pathlib import Path

for p in Path(".").iterdir():
    print(p.name)

.iterdir() yields Path objects for every immediate child of the directory β€” files, subdirectories, and symlinks. It's lazy: even on directories with millions of entries it returns an iterator that you can filter without loading everything into memory.

For recursive listing use .rglob(pattern) β€” 'r' for recursive. Path('.').rglob('*.py') walks the entire tree and yields every Python file. Path('src').rglob('*.tsx') is similarly restricted to a subtree.

Filter with a comprehension: [p for p in Path('.').iterdir() if p.is_file() and p.suffix == '.txt']. Avoid os.listdir() in new code β€” it returns strings and doesn't give you the Path methods.

Variations

Only .py files, recursive

for p in Path(".").rglob("*.py"):
    print(p)

rglob does the whole tree in one call.

Only files, one level

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

Excludes subdirectories and hidden system entries.

Sorted by name

for p in sorted(Path(".").iterdir()):
    print(p.name)

iterdir has no guaranteed order β€” sorted() gives you a stable one.

Practise this in your browser

Every how-to has a live lesson. Free tier, no card.

Start free β†’

Unlock every lesson

Pro β€” $12/mo, unlimited AI, cancel any time.

See Pro plans β†’

Get one Python lesson + one career idea every Friday

No spam, no "buy our course now". Three bullets, every Friday. Unsubscribe with one click.

Related how-tos