是否有一种方法可以从Python内部获得类似于shell上的mkdir -p的功能。我正在寻找一个解决方案,而不是系统调用。我确信代码少于20行,我想知道是否有人已经写了它?
当前回答
如果文件已经存在,Mkdir -p会给出一个错误:
$ touch /tmp/foo
$ mkdir -p /tmp/foo
mkdir: cannot create directory `/tmp/foo': File exists
因此,对前面建议的改进是,如果os.path.isdir返回False(在检查errno.EEXIST时),将重新引发异常。
(更新)看看这个高度相似的问题;我同意公认的答案(和注意事项),除了我建议os.path.isdir而不是os.path.exists。
(更新)根据评论中的建议,完整的功能看起来像:
import os
def mkdirp(directory):
if not os.path.isdir(directory):
os.makedirs(directory)
其他回答
使用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.
这比捕获异常更容易:
import os
if not os.path.exists(...):
os.makedirs(...)
这种方法需要两次系统调用,在某些环境/条件下更容易受到竞争条件的影响。如果您正在编写比在受控环境中运行的简单的一次性脚本更复杂的东西,那么您最好使用只需要一次系统调用的可接受答案。
更新2012-07-27
我很想删除这个答案,但我认为下面的评论有价值。因此,我将其转换为wiki。
我认为Asa的回答基本上是正确的,但你也可以将其扩展一点,使其更像mkdir -p:
import os
def mkdir_path(path):
if not os.access(path, os.F_OK):
os.mkdirs(path)
or
import os
import errno
def mkdir_path(path):
try:
os.mkdirs(path)
except os.error, e:
if e.errno != errno.EEXIST:
raise
这两种方法都可以处理路径已经静默存在但会出现其他错误的情况。
最近,我发现这个distutils.dir_util.mkpath:
In [17]: from distutils.dir_util import mkpath
In [18]: mkpath('./foo/bar')
Out[18]: ['foo', 'foo/bar']
在Python中>=3.2,这是
os.makedirs(path, exist_ok=True)
在早期版本中,使用@tzot的答案。
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 使用try和。Python中的if
- 如何在Python中获得所有直接子目录