自动创建文件输出目录[重复]

本文翻译自: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.existsos.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.existsos.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")
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值