Skip to main content

Make directory and intermediate directories as required.

import os


def mkdir_p(directory_name):
    """Make directory and intermediate directories as required.

    The way a good mkdir should work.

    - already exists, silently complete
    - regular file in the way, raise an exception
    - parent directory(ies) does not exist, make them as well

    http://code.activestate.com/recipes/82465-a-friendly-mkdir/
    """
    if os.path.isdir(directory_name):
        pass
    elif os.path.isfile(directory_name):
        raise OSError("a file with the same name as the desired "
                      "dir, '%s', already exists." % directory_name)
    else:
        head, tail = os.path.split(directory_name)
        if head and not os.path.isdir(head):
            mkdir_p(head)
        if tail:
            os.mkdir(directory_name)