本文翻译自:Automatically creating directories with file output [duplicate]
Possible Duplicate: 可能重复:
mkdir -p functionality in python python中的mkdir -p功能
Say I want to make a file: 说我想制作一个文件:
filename = "/foo/bar/baz.txt"
with open(filename, "w") as f:
f.write("FOOBAR")
This gives an IOError
, since /foo/bar
does not exist. 这给出了一个IOError
,因为/foo/bar
不存在。
What is the most pythonic way to generate those directories automatically? 什么是自动生成这些目录的最pythonic方式? Is it necessary for me explicitly call os.path.exists
and os.mkdir
on every single one (ie, /foo, then /foo/bar)? 是否有必要在每一个上显式调用os.path.exists
和os.mkdir
(即/ foo,然后是/ foo / bar)?
#1楼
参考:https://stackoom.com/question/Qwmn/自动创建文件输出目录-重复
#2楼
The os.makedirs
function does this. os.makedirs
函数就是这样做的。 Try the following: 请尝试以下方法:
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")
The reason to add the try-except
block is to handle the case when the directory was created between the os.path.exists
and the os.makedirs
calls, so that to protect us from race conditions. 添加try-except
块的原因是为了处理在os.path.exists
和os.makedirs
调用之间创建目录的情况,以便保护我们免受竞争条件的影响。
In Python 3.2+, there is a more elegant way that avoids the race condition above: 在Python 3.2+中,有一种更优雅的方式可以避免上面的竞争条件:
filename = "/foo/bar/baz.txt"¨
os.makedirs(os.path.dirname(filename), exist_ok=True)
with open(filename, "w") as f:
f.write("FOOBAR")