这是四个路径:
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().
更多推荐
制作路径中所有目录的优雅方式
发布评论