有没有办法从Python中获得类似于shell上的mkdir -p
的功能?我正在寻找不同于系统调用的解决方案.我敢肯定代码不到20行,我想知道是不是有人已经写好了?
有没有办法从Python中获得类似于shell上的mkdir -p
的功能?我正在寻找不同于系统调用的解决方案.我敢肯定代码不到20行,我想知道是不是有人已经写好了?
对于Python≥ 3.5,使用pathlib.Path.mkdir
:
import pathlib
pathlib.Path("/tmp/path/to/desired/directory").mkdir(parents=True, exist_ok=True)
Python 3.5中添加了exist_ok
参数.
对于Pythonos.makedirs
3.2,当≥为True
时,它具有optional third argument exist_ok
,该optional third argument exist_ok
启用mkdir -p
功能-unlessmode
被提供,并且现有目录具有与预期目录不同的权限;在这种情况下,OSError
如前所述:
import os
os.makedirs("/tmp/path/to/desired/directory", exist_ok=True)
对于更旧版本的Python,可以使用os.makedirs
并忽略错误:
import errno
import os
def mkdir_p(path):
try:
os.makedirs(path)
except OSError as exc: # Python ≥ 2.5
if exc.errno == errno.EEXIST and os.path.isdir(path):
pass
# possibly handle other errno cases here, otherwise finally:
else:
raise