Home >Backend Development >Python Tutorial >How to Create a Directory and its Missing Parent Directories in Python?
Creating a Directory and Missing Parent Directories using Python
Q: How can I create a directory at a specified path while also creating any missing parent directories along that path?
To achieve this functionality in Python ≥ 3.5, utilize pathlib.Path.mkdir:
from pathlib import Path Path("/my/directory").mkdir(parents=True, exist_ok=True)
For earlier Python versions, consider the following approaches:
Approach 1: Utilize os.path.exists and os.makedirs
import os if not os.path.exists(directory): os.makedirs(directory)
While this approach is simple, it poses a potential race condition.
Approach 2: Handle Potential Race Condition
import os, errno try: os.makedirs(directory) except OSError as e: if e.errno != errno.EEXIST: raise
This option addresses the race condition by catching and examining the error code.
Modern Python Improvements:
Python versions 3.3 and 3.2 introduce improvements:
try: os.makedirs("path/to/directory") except FileExistsError: # directory already exists pass
os.makedirs("path/to/directory", exist_ok=True) # succeeds even if directory exists.
The above is the detailed content of How to Create a Directory and its Missing Parent Directories in Python?. For more information, please follow other related articles on the PHP Chinese website!