Python 中的 mkdir -p 功能 [英] mkdir -p functionality in Python

查看:48
本文介绍了Python 中的 mkdir -p 功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法从 Python 中在 shell 上获得类似于 mkdir -p 的功能.我正在寻找系统调用以外的解决方案.代码肯定不到20行,不知道有没有人写过?

Is there a way to get functionality similar to mkdir -p on the shell from within Python. I am looking for a solution other than a system call. I am sure the code is less than 20 lines, and I am wondering if someone has already written it?

推荐答案

对于 Python ≥ 3.5,使用 pathlib.Path.mkdir:

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

import pathlib
pathlib.Path("/tmp/path/to/desired/directory").mkdir(parents=True, exist_ok=True)

exist_ok 参数是在 Python 3.5 中添加的.

The exist_ok parameter was added in Python 3.5.

对于 Python ≥ 3.2,os.makedirs 有一个 可选的第三个参数 exist_ok,当 True 启用 mkdir -p 功能时——除非 mode 是提供并且现有目录具有与预期目录不同的权限;在这种情况下,OSError 会像以前一样引发:

For Python ≥ 3.2, os.makedirs has an optional third argument exist_ok that, when True, enables the mkdir -p functionality—unless mode is provided and the existing directory has different permissions than the intended ones; in that case, OSError is raised as previously:

import os
os.makedirs("/tmp/path/to/desired/directory", exist_ok=True)


对于更旧版本的 Python,您可以使用 os.makedirs 并忽略错误:

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

这篇关于Python 中的 mkdir -p 功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆