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

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

Barbara Streisand
Barbara StreisandOriginal
2024-10-28 19:40:29362browse

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>

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>

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>

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!

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