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

自古美人都是妖i 提交于 2020-08-07 11:30:27

问题:

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? 检查文件目录是否存在的最优雅方法是什么?如果不存在,则使用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). 不知何故,我错过了os.path.exists (感谢kanja,Blair和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://stackoom.com/question/194K/如何安全地创建嵌套目录
参考二: https://oldbug.net/q/194K/How-can-I-safely-create-a-nested-directory
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!