Welcome, guest | Sign In | My Account | Store | Cart

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

Python, 18 lines
 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)

2 comments

Scott Tsai 16 years, 5 months ago  # | flag

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

Steve Carter 8 years, 9 months ago  # | flag

... but does throw an exception if the dir already exists.

Created by Trent Mick on Thu, 18 Oct 2001 (PSF)
Python recipes (4591)
Trent Mick's recipes (28)

Required Modules

  • (none specified)

Other Information and Tasks