Is there a way to get functionality similar to
mkdir -p on the shell from within Python. I am looking for a solution other than a system call. I am sure the code is less than 20 lines, and I am wondering if someone has already written it?
mkdir -p functionality as follows:
import errno import os def mkdir_p(path): try: os.makedirs(path) except OSError as exc: # Python >2.5 if exc.errno == errno.EEXIST and os.path.isdir(path): pass else: raise
For Python ≥ 3.2,
os.makedirs has an optional third argument
exist_ok that, when true, enables the
mkdir -p functionality —unless
mode is provided and the existing directory has different permissions than the intended ones; in that case,
OSError is raised as previously.
For Python ≥ 3.5, there is also
import pathlib pathlib.Path("/tmp/path/to/desired/directory").mkdir(parents=True, exist_ok=True)
exist_ok parameter was added in Python 3.5.