使用文件输出自动创建目录

2024-05-23 20:58:16 发布

您现在位置:Python中文网/ 问答频道 /正文

Possible Duplicate:
mkdir -p functionality in python

假设我想制作一个文件:

filename = "/foo/bar/baz.txt"

with open(filename, "w") as f:
    f.write("FOOBAR")

这将给出一个IOError,因为/foo/bar不存在。

自动生成这些目录的最变态的方法是什么?对我来说,有必要对每个单独的对象(即/foo,然后/foo/bar)显式调用os.path.existsos.mkdir


Tags: 文件intxtfooosaswithbar
1条回答
网友
1楼 · 发布于 2024-05-23 20:58:16

^{}函数会执行此操作。请尝试以下操作:

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.existsos.makedirs调用之间创建目录的情况,以便保护我们不受竞争条件的影响。


在Python 3.2+中,有一个more elegant way可以避免上面的竞争条件:

filename = "/foo/bar/baz.txt"¨
os.makedirs(os.path.dirname(filename), exist_ok=True)
with open(filename, "w") as f:
    f.write("FOOBAR")

相关问题 更多 >