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

Susan Sarandon
Release: 2024-11-01 03:15:28
Original
509 people have browsed it

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

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

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

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!