Python Glossary Русский

all Python 3osfunction

os.walk()

traversal

A generator that walks a directory tree. For every folder it yields (dirpath, dirnames, filenames).

Syntax

os.walk(top, topdown=True, onerror=None, followlinks=False)

To skip directories, edit dirnames in place with topdown=True: dirnames[:] = [d for d in dirnames if d != '.git']. Rebinding the name does not work — walk looks at the very same list. By default errors reading directories are silently skipped: an unreadable folder simply drops out of the walk; pass onerror to hear about them. walk does not descend into symlinked directories unless followlinks=True.

Examples

import os
for root, dirs, files in os.walk('.'):
    print(root)  # → текущая папка
all_py = []
for root, dirs, files in os.walk('.'):
    for f in files:
        if f.endswith('.py'):
            all_py.append(os.path.join(root, f))  # → все .py файлы рекурсивно
total = sum(len(files) for _, _, files in os.walk('.'))  # → общее число файлов
print(total)  # → кол-во файлов

See also

Open in the full glossarydocs.python.orgReport an inaccuracy