Change os.makedirs to handle existing directory

Wanderer wanderer at dialup4less.com
Mon Feb 13 17:59:59 EST 2012


I think wanting to create a directory if one doesn't exist or do
nothing if it does exist and just use the existing directory is a
fairly normal programming need. Apparently this is somewhat
complicated in Python. If you use

if not os.path.exists(dirName):
    os.makedirs(dirName)

you create a race condition. If you use try:

try:
    os.makedirs(dirName)
except OSError:
    pass

Now you're silencing too many errors, so you need to select which
errors to silence. You can check to see if the directory already
exists and assume that the directory already existing is the cause of
the error.

try:
    os.makedirs(dirName)
except OSError:
    if os.path.exists(dirName):
        # We are nearly safe
        pass
    else:
        # There was an error on creation, so make sure we know about
it
        raise

or check the error type:

try:
    os.makedirs(dirName)
except OSError, e:
    if e.errno != errno.EEXIST:
        raise


IMHO, os.makedirs should do this for you with something like

os.makedirs(dirName, exist = False)

and have makedirs silence the error the 'right' way whatever that is,
without turning it into an exercise for the user.











More information about the Python-list mailing list