相关疑难解决方法(0)

如何在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)
Run Code Online (Sandbox Code Playgroud)

不知何故,我错过了os.path.exists(感谢kanja,Blair和Douglas).这就是我现在拥有的:

def ensure_dir(file_path):
    directory = os.path.dirname(file_path)
    if not os.path.exists(directory):
        os.makedirs(directory)
Run Code Online (Sandbox Code Playgroud)

是否有"开放"的标志,这会自动发生?

python directory operating-system exception path

3909
推荐指数
28
解决办法
245万
查看次数

标签 统计

directory ×1

exception ×1

operating-system ×1

path ×1

python ×1