如何安全地创建嵌套目录?
问题: 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