【问题标题】:Automatically creating directories with file output [duplicate]使用文件输出自动创建目录[重复]
【发布时间】:2012-09-13 02:30:08
【问题描述】:

可能重复:
mkdir -p functionality in python

假设我要制作一个文件:

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

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

这给出了IOError,因为/foo/bar 不存在。

自动生成这些目录的最 Pythonic 方式是什么?我是否有必要在每一个上显式调用 os.path.existsos.mkdir(即 /foo,然后 /foo/bar)?

【问题讨论】:

    标签: python file-io


    【解决方案1】:

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

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


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

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

    【讨论】:

    • 只需要查看os.mkdir 并阅读有关另一个功能的文档 :)
    • 这里有一个稍微不同的方法:stackoverflow.com/a/14364249/1317713Thoughts?
    • 由于os.makedirs使用EAFP,是否需要初始if not os.path.exists
    • PermissionError: [Errno 13] Permission denied: '/foo'
    • 与 Pathlib:from pathlib import Path; output_file = Path("/foo/bar/baz.txt"); output_file.parent.mkdir(exist_ok=True, parents=True); output_file.write_text("FOOBAR")
    猜你喜欢
    • 2013-09-11
    • 1970-01-01
    • 1970-01-01
    • 2023-03-05
    • 1970-01-01
    • 2013-10-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多