This question already has an answer here:
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, and I am wondering if someone has already written it?
I think Asa's answer is essentially correct, but you could extend it a little to act more like
mkdir -p
, either:or
These both handle the case where the path already exists silently but let other errors bubble up.
I've had success with the following personally, but my function should probably be called something like 'ensure this directory exists':
This is easier than trapping the exception:
Disclaimer This approach requires two system calls which is more susceptible to race conditions under certain environments/conditions. If you're writing something more sophisticated than a simple throwaway script running in a controlled environment, you're better off going with the accepted answer that requires only one system call.
UPDATE 2012-07-27
I'm tempted to delete this answer, but I think there's value in the comment thread below. As such, I'm converting it to a wiki.
In Python >=3.2, that's
In earlier versions, use @tzot's answer.
based on @Dave C's answer but with a bug fixed where part of the tree already exists
mkdir -p
functionality as follows:Update
For Python ≥ 3.2,
os.makedirs
has an optional third argumentexist_ok
that, when true, enables themkdir -p
functionality —unlessmode
is provided and the existing directory has different permissions than the intended ones; in that case,OSError
is raised as previously.Update 2
For Python ≥ 3.5, there is also
pathlib.Path.mkdir
:The
exist_ok
parameter was added in Python 3.5.