且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

自动创建文件输出目录

更新时间:2023-11-29 19:29:10

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 调用,这样可以保护我们免受竞争的影响。






更优雅的方式这样可以避免上面的争夺情况:

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