Elegant way to make all dirs in a path

て烟熏妆下的殇ゞ 提交于 2019-12-12 07:38:58

问题


Here are four paths:

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?

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.


回答1:


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

The documentation states:

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.

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




回答2:


On Python 3.6+ you can do:

import pathlib

path = pathlib.Path(p4)
path.parent.mkdir(parents=True, exist_ok=True)


来源:https://stackoverflow.com/questions/5210778/elegant-way-to-make-all-dirs-in-a-path

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!