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
Release: 2024-12-15 12:29:19
Original
456 people have browsed it

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)
Copy after login

Older Python Versions:

Using os module:

import os
if not os.path.exists(directory):
    os.makedirs(directory)
Copy after login

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
Copy after login

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
Copy after login

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.
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template