If you are searching how to safely create a nested directory in Python, use the following example code:
from pathlib import Path
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:
os.path.exists, and consider
os.makedirs for the creation.
if not os.path.exists(directory):
As noted in comments and elsewhere, there’s a race condition – if the directory is created between the
os.path.exists and the
os.makedirs calls, the
os.makedirs will fail with an
OSError. Unfortunately, blanket-catching
OSError and 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.
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.