在Python 3.2+中,使用OP请求的API,您可以优雅地 https://docs.python.org/3/library/os.html#os.makedirs请执行下列操作:
import os
filename = "/foo/bar/baz.txt"
os.makedirs(os.path.dirname(filename), exist_ok=True)
with open(filename, "w") as f:
f.write("FOOBAR")
对于 Pathlib 模块(在 Python 3.4 中引入),有一种替代语法(感谢 David258):
from pathlib import Path
output_file = Path("/foo/bar/baz.txt")
output_file.parent.mkdir(exist_ok=True, parents=True)
output_file.write_text("FOOBAR")
在较旧的 python 中,有一种不太优雅的方法:
The os.makedirs http://docs.python.org/library/os.html#os.makedirs函数执行此操作。请尝试以下操作:
import os
import errno
filename = "/foo/bar/baz.txt"
if not os.path.exists(os.path.dirname(filename)):
try:
os.makedirs(os.path.dirname(filename))
except OSError as exc: # Guard against race condition
if exc.errno != errno.EEXIST:
raise
with open(filename, "w") as f:
f.write("FOOBAR")
添加的原因try-except
块是处理在之间创建目录时的情况os.path.exists
和os.makedirs
调用,以便保护我们免受竞争条件的影响。