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

查看:135
本文介绍了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?

推荐答案

对于≥3.5的Python,请使用 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 ,当,启用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并忽略该错误:

For even older versions of Python you can use os.makedirs and ignore the error:

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

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

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