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

Phi*_*hil 301 python file-io

可能重复:
python中的mkdir -p功能

说我想制作一个文件:

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

with open(filename, "w") as f:
    f.write("FOOBAR")
Run Code Online (Sandbox Code Playgroud)

这给了一个IOError,因为/foo/bar不存在.

什么是自动生成这些目录的最pythonic方式?难道真的要我明确调用os.path.existsos.mkdir在每个单独的一个(即/富,则/富/条)?

Kru*_*lur 570

os.makedirs功能可以做到这一点 请尝试以下方法:

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")
Run Code Online (Sandbox Code Playgroud)

添加try-except块的原因是处理os.path.existsos.makedirs调用和调用之间创建目录的情况,以便保护我们免受竞争条件的影响.


在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")
Run Code Online (Sandbox Code Playgroud)

  • 这里有一个稍微不同的方法:http://stackoverflow.com/a/14364249/1317713想法? (4认同)
  • 与 Pathlib: `from pathlib import Path; 输出文件=路径(“/foo/bar/baz.txt”); output_file.parent.mkdir(exist_ok=True, 父母=True); 输出文件.write_text(“FOOBAR”)` (4认同)
  • PermissionError:[Errno 13]权限被拒绝:'/ foo' (3认同)
  • 只需要看看`os.mkdir`并阅读另外一个函数的文档:) (2认同)
  • 因为`os.makedirs`使用[EAFP](https://docs.python.org/2/glossary.html#term-eafp),是否需要初始`if not os.path.exists`? (2认同)
  • 很好 但是请注意,您可能需要检查文件名是否包含路径,或者尝试创建名称为空的路径(例如,从“ baz.txt”派生的路径),将报错“ FileNotFoundError:[错误2]没有此类文件或目录:”显然,只有在您写入当前工作目录时才会发生这种情况。 (2认同)