How to Create Nested Directories in Python: A Guide for All Versions

Patricia Arquette
Release: 2024-10-29 05:48:31
Original
473 people have browsed it

How to Create Nested Directories in Python: A Guide for All Versions

Creating Directories with mkdir() Functionality in Python

The widely-used Unix and Windows command line utility mkdir offers a highly convenient -p flag, which enables the creation of nested directories. For those working within the Python programming language, a similar functionality can be achieved natively, obviating the need for external system calls.

Python 3.5 and Above: pathlib.Path.mkdir

In Python versions 3.5 and later, the pathlib.Path.mkdir method provides a straightforward solution. The following snippet illustrates its usage with the exist_ok parameter:

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

Python 3.2 to 3.4: os.makedirs

For Python versions between 3.2 and 3.4, os.makedirs can be employed with the exist_ok argument:

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

Python 2.5 to 3.1: Handling Errors in os.makedirs

In earlier Python versions (2.5 to 3.1), the following approach handles errors encountered with os.makedirs:

<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
        else:
            raise</code>
Copy after login

The above is the detailed content of How to Create Nested Directories in Python: A Guide for All Versions. 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