Python Glossary Русский

Python 3.4+pathlibfunction

.mkdir()

operations

Create a directory; `parents=True` also creates missing parents and `exist_ok=True` tolerates an existing one.

Syntax

p.mkdir(parents=True, exist_ok=True)

Without parents=True a missing parent raises FileNotFoundError, not FileExistsError — two different errors that are easy to confuse while debugging. exist_ok=True only forgives an existing directory; if a regular file sits at that path you still get FileExistsError. Don't test exists() first — exist_ok=True is shorter and race-free, since the directory may appear between the check and the call.

Examples

from pathlib import Path
Path('new_dir').mkdir(exist_ok=True)
print(Path('new_dir').is_dir())   # → True
Path('a/b/c').mkdir(parents=True, exist_ok=True)
print(Path('a/b/c').is_dir())   # → True (parents=True создаёт всю цепочку)
try:
    Path('new_dir').mkdir()
except FileExistsError as e:
    print(type(e).__name__)   # → FileExistsError (без exist_ok=True)
try:
    Path('x/y/z').mkdir()
except FileNotFoundError as e:
    print(type(e).__name__)   # → FileNotFoundError (без parents=True)

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy