Creating Directories and Their Parents with Python
In the realm of file systems, it's often necessary to create directories, both at the specified path and any missing parent directories along the way. This mimics the functionality of Bash's mkdir -p command.
Modern Python (≥ 3.5):
Python's pathlib module provides a convenient way to handle this:
from pathlib import Path Path("/my/directory").mkdir(parents=True, exist_ok=True)
Older Python Versions:
Using os module:
import os if not os.path.exists(directory): os.makedirs(directory)
This approach has a potential race condition, as noted by comments. To address this, you could use a second os.path.exists call or trap the OSError and examine the embedded error code:
import os, errno try: os.makedirs(directory) except OSError as e: if e.errno != errno.EEXIST: raise
However, this introduces the risk of missing other errors.
Improved Python Versions:
Python 3.3 introduces FileExistsError, which simplifies error handling:
try: os.makedirs("path/to/directory") except FileExistsError: # directory already exists pass
Python 3.2 also adds the exist_ok argument to os.makedirs:
os.makedirs("path/to/directory", exist_ok=True) # succeeds even if directory exists.
The above is the detailed content of How Can I Create Directories and Their Parent Directories in Python?. For more information, please follow other related articles on the PHP Chinese website!