有没有办法从 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)
exist_ok
参数是在 Python 3.5 中添加的。
对于 Python ≥ 3.2,os.makedirs
有一个 optional third argument exist_ok
即,当 True
时,启用 mkdir -p
功能——除非 mode
提供且现有目录有不同超出预期的权限;在这种情况下,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
关于python - Python 中的 mkdir -p 功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/600268/