问题:
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
来源:oschina
链接:https://my.oschina.net/u/4428122/blog/4454454