制作路径中所有目录的优雅方式

编程入门 行业动态 更新时间:2024-10-23 04:59:12
本文介绍了制作路径中所有目录的优雅方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

这是四个路径:

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.

推荐答案

您正在寻找 os.makedirs() 完全满足您的需求.

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().

更多推荐

制作路径中所有目录的优雅方式

本文发布于:2023-11-01 20:20:09,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1550316.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:路径   优雅   方式   目录

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!