If you want to create a directory in Python, but only if it doesn’t exist, you have the following option.

This comes up constantly when writing scripts that generate output files — you need the target directory to exist but don’t want the script to crash if it’s already there. The pathlib approach is the cleanest since exist_ok=True handles the race condition where another process might create the directory between your check and your mkdir call. The parents=True flag also creates any missing intermediate directories, similar to mkdir -p in bash.

Using Python 3.5 or newer?

from pathlib import Path
Path("/your/directory").mkdir(parents=True, exist_ok=True)

Alternative option

import os
if not os.path.exists("/your/directory"):
  os.makedirs("/your/directory")