Change os.makedirs to handle existing directory

W

Wanderer

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.
 
A

Andrew Berg

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top