I'll note that all of this is quite a bit more sane in python 3; FileExistsError
and PermissionError
are separate (subclass of OSError
) exceptions that you can catch, and os.makedirs
even has a exist_ok
kwarg to suppress the former when you're ok with the directory already existing.
If you want to inspect the reason for the OSError
, that info is in a tuple in e.args
(or optionally e.errno
if you just want to look at the error code):
try:
os.makedirs('/etc/python')
except OSError as e:
print e.args
(17, 'File exists')
try:
os.makedirs('/etc/stuff')
except OSError as e:
print e.args
(13, 'Permission denied')
try:
os.makedirs('/etc/stuff')
except OSError as e:
print e.errno
13
So you'll have to do a bit of introspection and handle the two error codes differently in your except
block.