Is there a way to get functionality similar to mkdir -p
on the shell... from within python. I am looking for a solution other than a system call. I am sure the code is less than 20 lines... really I am wondering if someone has already written it?
views:
13516answers:
6This should be all you need
import os
os.makedirs('/path/to/create')
I think Asa's answer is essentially correct, but you could extend it a little to act more like mkdir -p
, either:
import os
def mkdir_path(path):
if not os.access(path, os.F_OK):
os.mkdirs(path)
or
import os
import errno
def mkdir_path(path):
try:
os.mkdirs(path)
except os.error, e:
if e.errno != errno.EEXIST:
raise
These both handle the case where the path already exists silently but let other errors bubble up.
mkdir -p
functionality as follows:
import os, errno
def mkdir_p(path):
try:
os.makedirs(path)
except OSError as exc: # Python >2.5
if exc.errno == errno.EEXIST:
pass
else: raise
mkdir -p
gives you an error if you the file already exists:
$ touch /tmp/foo
$ mkdir -p /tmp/foo
mkdir: cannot create directory `/tmp/foo': File exists
So a refinement to the previous suggestions would be to re-raise
the exception if os.path.isdir
returns False
(when checking for errno.EEXIST
).
(Update) See also this highly similar question; I agree with the accepted answer (and caveats) except I would recommend os.path.isdir
instead of os.path.exists
.
(Update) Per a suggestion in the comments, the full function would look like:
import os
def mkdirp(directory):
if not os.path.isdir(directory):
os.makedirs(directory)
This is easier than trapping the exception:
import os
if not os.path.exists (...):
os.makedirs (...)
UPDATE 4/20/2010
I originally presented this solution because I assumed the OP was looking for something quick and dirty, perhaps for a script or a program that doesn't need to guard against a race condition where another process creates the path out from underneath it. If your program must guard against that sort of condition, don't use this solution, instead go with the accepted solution provided by ΤΖΩΤΖΙΟΥ.
However, this solution can be used for simple, throwaway code or something that will run in a controlled environment where you know for certain you will not encounter the race condition mentioned above.
When in doubt, use the accepted solution as it's correct in more cases than this one. This solution is not necessarily wrong, but it can be broken when used naively.
eh..., "mkdir -p" creates all non-existing parents as well.
That the above solutions do not.