检查文件目录是否存在的最优雅方法是什么,如果不存在,使用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)
是否有"开放"的标志,这会自动发生?