mkdir -p functionality in Python


Question

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?

1
725
11/4/2015 4:19:13 PM

Accepted Answer

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

Update

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.

Update 2

For Python ≥ 3.5, there is also pathlib.Path.mkdir:

import pathlib

pathlib.Path("/tmp/path/to/desired/directory").mkdir(parents=True, exist_ok=True)

The exist_ok parameter was added in Python 3.5.

998
10/7/2018 4:04:05 PM

In Python >=3.2, that's

os.makedirs(path, exist_ok=True)

In earlier versions, use @tzot's answer.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon