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

检查文件目录是否存在的最优雅方法是什么,如果不存在,如何使用Python创建目录?这是我以前使用过的方法:

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)
不知何故,我错过了os.path.exists。现在推荐使用这个方法:
def ensure_dir(file_path):
    directory = os.path.dirname(file_path)
    if not os.path.exists(directory):
        os.makedirs(directory)



所属网站分类: python基础 > 模块,库


作者:追梦骚年

原文链接: http://www.pythonheidong.com/blog/article/33/

来源:python黑洞网 www.pythonheidong.com

猜你喜欢

转载自www.cnblogs.com/fuchen9527/p/10962180.html
今日推荐