Home >Backend Development >Python Tutorial >How to Create a Directory and its Missing Parent Directories in Python?

How to Create a Directory and its Missing Parent Directories in Python?

Linda Hamilton
Linda HamiltonOriginal
2024-12-21 10:17:09963browse

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:

  • FileExistsError is exposed, allowing for cleaner error handling.
  • os.makedirs features the exist_ok keyword argument, enabling directory creation even if it already exists.
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!

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