Home  >  Article  >  Backend Development  >  How can I create directories in Python, including intermediate directories, if they don\'t already exist?

How can I create directories in Python, including intermediate directories, if they don\'t already exist?

Susan Sarandon
Susan SarandonOriginal
2024-11-01 03:15:28509browse

How can I create directories in Python, including intermediate directories, if they don't already exist?

mkdir -p functionality in Python (duplicate)

For Python ≥ 3.5, you can use pathlib.Path.mkdir:

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

Python≥3.5 introduced the exist_ok parameter.

For Python ≥ 3.2, os.makedirs has an optional third parameter exist_ok. When exist_ok is True, the mkdir -p function is available, unless mode is provided and the permissions of the existing directory are different than expected. ; In this case, OSError will be raised as before:

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

For earlier versions of Python, you can use os.makedirs and ignore the error:

<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
        # 还可以在此处理其他errno情况,否则:
        else:
            raise</code>

The above is the detailed content of How can I create directories in Python, including intermediate directories, if they don\'t already exist?. 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