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
Release: 2024-10-29 12:11:02
Original
653 people have browsed it

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

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

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

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!

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