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?
mkdir -p
gives you an error if the file already exists:So a refinement to the previous suggestions would be to re-
raise
the exception ifos.path.isdir
returnsFalse
(when checking forerrno.EEXIST
).(Update) See also this highly similar question; I agree with the accepted answer (and caveats) except I would recommend
os.path.isdir
instead ofos.path.exists
.(Update) Per a suggestion in the comments, the full function would look like:
With Pathlib from python3 standard library:
Function declaration;
usage :
As mentioned in the other solutions, we want to be able to hit the file system once while mimicking the behaviour of
mkdir -p
. I don't think that this is possible to do, but we should get as close as possible.Code first, explanation later:
As the comments to @tzot's answer indicate there are problems with checking whether you can create a directory before you actually create it: you can't tell whether someone has changed the file system in the meantime. That also fits in with Python's style of asking for forgiveness, not permission.
So the first thing we should do is try to make the directory, then if it goes wrong, work out why.
As Jacob Gabrielson points out, one of the cases we must look for is the case where a file already exists where we are trying to put the directory.
With
mkdir -p
:The analogous behaviour in Python would be to raise an exception.
So we have to work out if this was the case. Unfortunately, we can't. We get the same error message back from makedirs whether a directory exists (good) or a file exists preventing the creation of the directory (bad).
The only way to work out what happened is to inspect the file system again to see if there is a directory there. If there is, then return silently, otherwise raise the exception.
The only problem is that the file system may be in a different state now than when makedirs was called. eg: a file existed causing makedirs to fail, but now a directory is in its place. That doesn't really matter that much, because the the function will only exit silently without raising an exception when at the time of the last file system call the directory existed.
Recently, I found this distutils.dir_util.mkpath: