2008-11-07 18:56
采纳率: 0%
浏览 574

如何在 Python 中安全地创建嵌套目录?

What is the most elegant way to check if the directory a file is going to be written to exists, and if not, create the directory using Python? Here is what I tried:

import os

file_path = "/my/directory/filename.txt"
directory = os.path.dirname(file_path)


f = file(filename)

Somehow, I missed os.path.exists (thanks kanja, Blair, and Douglas). This is what I have now:

def ensure_dir(file_path):
    directory = os.path.dirname(file_path)
    if not os.path.exists(directory):

Is there a flag for "open", that makes this happen automatically?


  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

25条回答 默认 最新

  • MAO-EYE 2008-11-07 19:06

    I see two answers with good qualities, each with a small flaw, so I will give my take on it:

    Try os.path.exists, and consider os.makedirs for the creation.

    import os
    if not os.path.exists(directory):

    As noted in comments and elsewhere, there's a race condition - if the directory is created between the os.path.exists and the os.makedirs calls, the os.makedirs will fail with an OSError. Unfortunately, blanket-catching OSError and continuing is not foolproof, as it will ignore a failure to create the directory due to other factors, such as insufficient permissions, full disk, etc.

    One option would be to trap the OSError and examine the embedded error code (see Is there a cross-platform way of getting information from Python’s OSError):

    import os, errno
    except OSError as e:
        if e.errno != errno.EEXIST:

    Alternatively, there could be a second os.path.exists, but suppose another created the directory after the first check, then removed it before the second one - we could still be fooled.

    Depending on the application, the danger of concurrent operations may be more or less than the danger posed by other factors such as file permissions. The developer would have to know more about the particular application being developed and its expected environment before choosing an implementation.

    解决 无用
    打赏 举报

相关推荐 更多相似问题