Home > Backend Development > Python Tutorial > How to Simulate the `mkdir -p` Functionality in Python?

How to Simulate the `mkdir -p` Functionality in Python?

Barbara Streisand
Release: 2024-10-28 19:40:29
Original
448 people have browsed it

How to Simulate the `mkdir -p` Functionality in Python?

Python mkdir -p Equivalent

For simulating the mkdir -p functionality of the shell from within Python, there are several approaches available.

Python 3.5 and Later

Python 3.5 introduces the pathlib.Path.mkdir function, which includes the parents and exist_ok parameters. By setting parents to True and exist_ok to True, it creates the directory and any non-existent parent directories without raising an error:

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

Python 3.2 and Later

For Python 3.2 and above, the os.makedirs function has an optional third argument, exist_ok, which can be set to True to achieve the same behavior:

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

Earlier Python Versions

For older versions of Python, you can use the os.makedirs function and catch the OSError exception when the directory already exists using the following code:

<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
        # possibly handle other errno cases here, otherwise finally:
        else:
            raise</code>
Copy after login

The above is the detailed content of How to Simulate 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