Implementing 'mkdir-p'

Asked 2 years ago, Updated 2 years ago, 82 views

You must create a function such as mkdir -p in the shell. Can I make it any other way than system call? I want it to be a short code with about 20 lines.

python mkdir

2022-09-22 22:31

1 Answers

The code is different depending on the Python version.

import os, errno

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

In Python 3.2 and later, the third factor exist_ok of osist_ok exist_ok = True functions like mkdir -p. However, OSError will occur if you cannot access the existing directory with mode.

import os, errno

def mkdir_p(path):
    try:
        os.makedirs(path, exist_ok=True) #python >= 3.2
    except OSError as exc: #Python > 2.5
        Rise #If you cannot access an existing directory

Click the following link to view documents based on Python version


2022-09-22 22:31

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.