ActiveState Powered by ActiveState

Recipe 82465: a friendly mkdir()


A more friendly mkdir() than Python's standard os.mkdir(). Limitations: it doesn't take the optional 'mode' argument yet.

Python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
def _mkdir(newdir):
    """works the way a good mkdir should :)
        - already exists, silently complete
        - regular file in the way, raise an exception
        - parent directory(ies) does not exist, make them as well
    """
    if os.path.isdir(newdir):
        pass
    elif os.path.isfile(newdir):
        raise OSError("a file with the same name as the desired " \
                      "dir, '%s', already exists." % newdir)
    else:
        head, tail = os.path.split(newdir)
        if head and not os.path.isdir(head):
            _mkdir(head)
        #print "_mkdir %s" % repr(newdir)
        if tail:
            os.mkdir(newdir)

Discussion

blah blah...

Comments

  1. 1. At 5:05 a.m. on 14 jun 2005, Scott Tsai said:

    os.makedirs(), the standard way. Note the standard os.makedirs() supports the make all intermediates behavior and also support the optional mode argument.

Sign in to comment