path – mkdir -p functionality in Python

path – mkdir -p functionality in Python

For Python ≥ 3.5, use 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.

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:

import os
os.makedirs(/tmp/path/to/desired/directory, exist_ok=True)

For even older versions of Python, you can use os.makedirs and ignore the error:

import errno    
import os

def mkdir_p(path):
    except OSError as exc:  # Python ≥ 2.5
        if exc.errno == errno.EEXIST and os.path.isdir(path):
        # possibly handle other errno cases here, otherwise finally:

In Python >=3.2, thats

os.makedirs(path, exist_ok=True)

In earlier versions, use @tzots answer.

path – mkdir -p functionality in Python

This is easier than trapping the exception:

import os
if not os.path.exists(...):

Disclaimer This approach requires two system calls which is more susceptible to race conditions under certain environments/conditions. If youre writing something more sophisticated than a simple throwaway script running in a controlled environment, youre better off going with the accepted answer that requires only one system call.

UPDATE 2012-07-27

Im tempted to delete this answer, but I think theres value in the comment thread below. As such, Im converting it to a wiki.

Leave a Reply

Your email address will not be published. Required fields are marked *