Home >Backend Development >Python Tutorial >How can I replicate the \'mkdir -p\' functionality in Python?

How can I replicate the \'mkdir -p\' functionality in Python?

Barbara Streisand
Barbara StreisandOriginal
2024-10-29 12:11:02629browse

How can I replicate the

Replicating the mkdir -p Functionality within Python

The mkdir -p command on Unix-like systems seamlessly creates a directory and its parent paths if they do not already exist. Is there a native Python solution that provides similar functionality?

Solution:

Fortunately, different versions of Python offer solutions for this task:

For Python 3.5 and Above:

Python 3.5 introduced pathlib.Path.mkdir with the parents=True and exist_ok=True arguments:

<code class="python">import pathlib
pathlib.Path("/tmp/path/to/desired/directory").mkdir(parents=True, exist_ok=True)</code>

For Python 3.2 and Above:

os.makedirs offers the exist_ok argument, which, when set to True, enables the mkdir -p functionality:

<code class="python">import os
os.makedirs("/tmp/path/to/desired/directory", exist_ok=True)</code>

For Older Python Versions:

For Python versions earlier than 3.2, you can use os.makedirs and ignore any errors related to existing directories:

<code class="python">import errno
import os

def mkdir_p(path):
    try:
        os.makedirs(path)
    except OSError as exc:  # Python ≥ 2.5
        if exc.errno == errno.EEXIST and os.path.isdir(path):
            pass
        # Handle other errors here or raise a generic exception.</code>

The above is the detailed content of How can I replicate the \'mkdir -p\' functionality 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