os.mkdir(path) returns OSError when directory does not exist os.mkdir(path) returns OSError when directory does not exist python python

os.mkdir(path) returns OSError when directory does not exist


Greg's answer is correct but doesn't go far enough. OSError has sub-error conditions, and you don't want to suppress them all every time. It's prudent to trap just expected OS errors.

Do additional checking before you decide to suppress the exception, like this:

import errnoimport ostry:    os.mkdir(dirname)except OSError as exc:    if exc.errno != errno.EEXIST:        raise    pass

You probably don't want to suppress errno.EACCES (Permission denied), errno.ENOSPC (No space left on device), errno.EROFS(Read-only file system) etc. Or maybe you do want to -- but that needs to be a conscious decision based on the specific logic of what you're building.

Greg's code suppresses all OS errors; that's unsafe just like except Exception is unsafe.


In Python 3.2 and above, you can use:

os.makedirs(path, exist_ok=True)

to avoid getting an exception if the directory already exists. This will still raise an exception if path exists and is not a directory.


Just check if the path exist. if not create it

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