You should note cjjclifford's code will throw an exception if the directory already exists. I would write it like this instead:
import errno
import os
DIRNAME = "/tmp/dir1/dir2/mydir"
try:
# os.makedirs will also create all the parent directories
os.makedirs(DIRNAME)
except OSError, err:
if err.errno == errno.EEXIST:
if os.path.isdir(DIRNAME):
print "directory already exists"
else:
print "file already exists, but not a directory"
raise # re-raise the exception
else:
raise
Main Topics
Browse All Topics





by: cjjcliffordPosted on 2005-06-07 at 07:15:49ID: 14162047
Use os.mkdir() to make tihe directory, os.path.exists() to see if the name exists, and os.path.isdir() to check if it is a directory...
>>> import os
>>> os.mkdir( '/tmp/mydir' )
>>> if os.path.exists( '/tmp/mkdir' ) and os.path.isdir( '/tmp/mydir' ):
... print 'exists and is dir'
... else:
... print 'does not exist or is not a directory!'
...
exists