是否有一种方法可以从Python内部获得类似于shell上的mkdir -p的功能。我正在寻找一个解决方案,而不是系统调用。我确信代码少于20行,我想知道是否有人已经写了它?
当前回答
函数声明;
import os
def mkdir_p(filename):
try:
folder=os.path.dirname(filename)
if not os.path.exists(folder):
os.makedirs(folder)
return True
except:
return False
用法:
filename = "./download/80c16ee665c8/upload/backup/mysql/2014-12-22/adclient_sql_2014-12-22-13-38.sql.gz"
if (mkdir_p(filename):
print "Created dir :%s" % (os.path.dirname(filename))
其他回答
import os
from os.path import join as join_paths
def mk_dir_recursive(dir_path):
if os.path.isdir(dir_path):
return
h, t = os.path.split(dir_path) # head/tail
if not os.path.isdir(h):
mk_dir_recursive(h)
new_path = join_paths(h, t)
if not os.path.isdir(new_path):
os.mkdir(new_path)
基于@Dave C的回答,但修复了部分树已经存在的错误
在Python中>=3.2,这是
os.makedirs(path, exist_ok=True)
在早期版本中,使用@tzot的答案。
最近,我发现这个distutils.dir_util.mkpath:
In [17]: from distutils.dir_util import mkpath
In [18]: mkpath('./foo/bar')
Out[18]: ['foo', 'foo/bar']
这比捕获异常更容易:
import os
if not os.path.exists(...):
os.makedirs(...)
这种方法需要两次系统调用,在某些环境/条件下更容易受到竞争条件的影响。如果您正在编写比在受控环境中运行的简单的一次性脚本更复杂的东西,那么您最好使用只需要一次系统调用的可接受答案。
更新2012-07-27
我很想删除这个答案,但我认为下面的评论有价值。因此,我将其转换为wiki。
使用python3标准库中的Pathlib:
Path(mypath).mkdir(parents=True, exist_ok=True)
If parents is true, any missing parents of this path are created as needed; they are created with the default permissions without taking mode into account (mimicking the POSIX mkdir -p command). If exist_ok is false (the default), an FileExistsError is raised if the target directory already exists. If exist_ok is true, FileExistsError exceptions will be ignored (same behavior as the POSIX mkdir -p command), but only if the last path component is not an existing non-directory file. Changed in version 3.5: The exist_ok parameter was added.
推荐文章
- 把if-elif-else语句放在一行中?
- 我如何结合两个数据框架?
- 如何计数列表中唯一值的出现
- 为什么Pycharm的检查人员抱怨“d ={}”?
- 如何JSON序列化集?
- 在python中,年龄从出生日期开始
- 使用pip安装SciPy
- 在Python中,我应该如何测试变量是否为None, True或False
- 如何在Python中从毫秒创建datetime ?
- 如何解窝(爆炸)在一个熊猫数据帧列,成多行
- 如何使用pip安装opencv ?
- 在pip冻结命令的输出中“pkg-resources==0.0.0”是什么
- 格式y轴为百分比
- 熊猫连接问题:列重叠但没有指定后缀
- 为什么空字典在Python中是一个危险的默认值?