Create nested directories in Python

Create missing parent directories with pathlib or os.makedirs, tolerate existing directories, and understand permissions, races, and path conflicts.

Best practices
Python programming and application logging

Use Path(path).mkdir(parents=True, exist_ok=True) to create missing parent directories and tolerate a destination directory that already exists.

from pathlib import Path

output = Path("output/reports/daily")
output.mkdir(parents=True, exist_ok=True)

This is convenient for repeatable setup. It still raises an error when a path component is a file, access is denied, or another filesystem problem prevents creation.

What the options control

  • parents=True creates missing parents. Without it, a missing parent causes FileNotFoundError.
  • exist_ok=True permits an existing directory. Without it, an existing destination causes FileExistsError.

The same basic operation is available through os.makedirs():

import os

os.makedirs("output/reports/daily", exist_ok=True)

os.makedirs() creates parents by design. Path.mkdir() creates only the final directory unless parents=True is supplied. The exist_ok option is available in os.makedirs() from Python 3.2 and in Path.mkdir() from Python 3.5.

Avoid a separate existence check

# Another process can create the directory between these calls.
if not os.path.exists("output/reports/daily"):
    os.makedirs("output/reports/daily")

Prefer the single exist_ok=True call. It handles the ordinary already-created-directory case, but creating a whole directory tree is not an atomic transaction. It does not protect against every concurrent rename, removal, or symbolic-link change, and earlier directories may remain if creation later fails.

FAQ

Can I set permissions? Both APIs accept mode, such as 0o755. On POSIX systems, the process umask affects the result. With current Python behavior, missing intermediate directories use default permissions rather than the final directory's explicit mode; existing directory permissions are not reset. Windows permission behavior differs.

Can the path be relative? Yes. It is resolved against the process's current working directory. When the location must be stable, choose an explicit application data path or derive it from a known base rather than assuming a particular launch directory.

Does “exist_ok” make arbitrary input safe? No. Validate user-controlled paths separately if they must remain inside a particular directory. The flag controls how existing directories are handled, not where the operation is allowed to write.

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