自动创建文件输出目录 [英] Automatically creating directories with file output

查看:133
本文介绍了自动创建文件输出目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能存在重复:

python中的mkdir -p功能


假设我想创建一个文件:

  filename =/foo/bar/baz.txt

with open (文件名w)作为f:
f.write(FOOBAR)

由于 / foo / bar 不存在,所以给出 IOError

自动生成这些目录的最好方法是什么?是否有必要在每一个显式调用 os.path.exists os.mkdir (即/ foo,那么/ foo / bar)?

解决方案

os.makedirs 这个功能。请尝试以下操作:

  import os 
import errno

filename =/ foo / bar / baz.txt
如果不是os.path.exists(os.path.dirname(filename)):
try:
os.makedirs(os.path.dirname(filename) )
,除了OSError,如exc:#防止竞争条件
如果exc.errno!= errno.EEXIST:
打开(文件名,w )作为f:
f.write(FOOBAR)

try-except block用于处理在 os.path.exists os.makedirs 调用,这样可以保护我们免受竞争的影响。






<在Python 3.2+中,有一个更优雅的方式这样可以避免上面的争夺情况:

  filename =/foo/bar/baz.txt\"¨
os。 makedirs(os.path.dirname(文件名), (开头的文件名为w)作为f:
f.write(FOOBAR)


Possible Duplicate:
mkdir -p functionality in python

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.

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)?

解决方案

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")

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.


In Python 3.2+, there is a more elegant way that avoids the race condition above:

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

这篇关于自动创建文件输出目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆