Home >Backend Development >Python Tutorial >How Can I Create Directories and Their Parent Directories in Python?

How Can I Create Directories and Their Parent Directories in Python?

Barbara Streisand
Barbara StreisandOriginal
2024-12-15 12:29:19460browse

How Can I Create Directories and Their Parent Directories in Python?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn