~Onlooker
2008-11-07 18:56
采纳率: 0%
浏览 734
已采纳

如何在 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)

try:
    os.stat(directory)
except:
    os.mkdir(directory)       

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):
        os.makedirs(directory)

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

转载于:https://stackoverflow.com/questions/273192/how-can-i-safely-create-a-nested-directory-in-python

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

25条回答 默认 最新

相关推荐 更多相似问题