Python Glossary Русский

Python 3.4+pathlibfunction

.iterdir()

traversal

Iterates over every file and subdirectory directly inside the given directory (not recursively).

Syntax

for item in p.iterdir(): ...

You get a one-shot iterator, not a list, and the order comes from the filesystem — wrap it in sorted() when the output has to be stable. Each item is a full Path including the parent directories, not a bare filename; .name gives you the name. It never descends: use rglob('*') for a recursive walk, or glob('*.txt') when you only want a pattern.

Examples

from pathlib import Path
# Свой каталог в текущем, а не системная временная папка: пример ничего не пишет снаружи.
base = Path('iterdir_demo')
base.mkdir(exist_ok=True)
(base / 'a.txt').write_text('a', encoding='utf-8')
(base / 'b.log').write_text('b', encoding='utf-8')
(base / 'sub').mkdir(exist_ok=True)
# Обход содержимого — не рекурсивный: только прямые дети
print(sorted((p.name, p.is_dir()) for p in base.iterdir()))
# → [('a.txt', False), ('b.log', False), ('sub', True)]
# Фильтрация
files = [p for p in base.iterdir() if p.is_file()]
dirs = [p for p in base.iterdir() if p.is_dir()]
print(len(files), len(dirs))  # → 2 1
# Рекурсивный обход — это уже rglob, а не iterdir
print(sorted(p.name for p in base.rglob('*.txt')))  # → ['a.txt']

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy