How do I create a directory at a given path, and also create any missing parent directories along that path? For example, the Bash command mkdir -p /path/to/nested/directory does this.
How do I create a directory at a given path, and also create any
Share
On Python ≥ 3.5, use
pathlib.Path.mkdir:For older versions of Python, I see two answers with good qualities, each with a small flaw, so I will give my take on it:
Try
os.path.exists, and consideros.makedirsfor the creation.As noted in comments and elsewhere, there’s a race condition – if the directory is created between the
os.path.existsand theos.makedirscalls, theos.makedirswill fail with anOSError. Unfortunately, blanket-catchingOSErrorand continuing is not foolproof, as it will ignore a failure to create the directory due to other factors, such as insufficient permissions, full disk, etc.One option would be to trap the
OSErrorand examine the embedded error code (see Is there a cross-platform way of getting information from Python’s OSError):Alternatively, there could be a second
os.path.exists, but suppose another created the directory after the first check, then removed it before the second one – we could still be fooled.Depending on the application, the danger of concurrent operations may be more or less than the danger posed by other factors such as file permissions. The developer would have to know more about the particular application being developed and its expected environment before choosing an implementation.
Modern versions of Python improve this code quite a bit, both by exposing
FileExistsError(in 3.3+)……and by allowing a keyword argument to
os.makedirscalledexist_ok(in 3.2+).