制作路径中所有目录的优雅方式 [英] Elegant way to make all dirs in a path

查看:80
本文介绍了制作路径中所有目录的优雅方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是四个路径:

p1=r'\foo\bar\foobar.txt'
p2=r'\foo\bar\foo\foo\foobar.txt'
p3=r'\foo\bar\foo\foo2\foobar.txt'
p4=r'\foo2\bar\foo\foo\foobar.txt'

驱动器上可能存在目录,也可能不存在目录.在每个路径中创建目录的最优雅方法是什么?

The directories may or may not exist on a drive. What would be the most elegant way to create the directories in each path?

我当时正在考虑循环使用os.path.split(),并使用os.path.exists检查目录,但我不知道有没有更好的方法.

I was thinking about using os.path.split() in a loop, and checking for a dir with os.path.exists, but I don't know it there's a better approach.

推荐答案

您正在寻找

You are looking for os.makedirs() which does exactly what you need.

文档指出:

递归目录创建功能. 像mkdir()一样,但是使所有 需要中级目录 包含叶子目录.加薪 错误异常,如果叶子 目录已存在或不能为 已创建.

Recursive directory creation function. Like mkdir(), but makes all intermediate-level directories needed to contain the leaf directory. Raises an error exception if the leaf directory already exists or cannot be created.

因为如果叶子目录已经存在,它将失败,因此您需要在调用os.makedirs()之前测试其存在性.

Because it fails if the leaf directory already exists you'll want to test for existence before calling os.makedirs().

这篇关于制作路径中所有目录的优雅方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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