自动创建带有文件输出的目录 [英] Automatically creating directories with file output
问题描述
可能的重复:
mkdir -p python 中的功能
说我想制作一个文件:
filename = "/foo/bar/baz.txt"
with open(filename, "w") as f:
f.write("FOOBAR")
这给出了一个 IOError
,因为 /foo/bar
不存在.
This gives an IOError
, since /foo/bar
does not exist.
自动生成这些目录的最pythonic 的方法是什么?我是否有必要在每一个(即/foo,然后是/foo/bar)上显式调用 os.path.exists
和 os.mkdir
?
What is the most pythonic way to generate those directories automatically? Is it necessary for me explicitly call os.path.exists
and os.mkdir
on every single one (i.e., /foo, then /foo/bar)?
推荐答案
os.makedirs
函数就是这样做的.请尝试以下操作:
The os.makedirs
function does this. 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")
添加try-except
块的原因是为了处理在os.path.exists
和os 之间创建目录的情况.makedirs
调用,以便保护我们免受竞争条件的影响.
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.
在 Python 3.2+ 中,有一种更优雅的方式 避免了上面的竞争条件:
In Python 3.2+, there is a more elegant way that avoids the race condition above:
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")
这篇关于自动创建带有文件输出的目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!