如果目录不存在,您可能还需要创建目录。
Source,如果它还在 SO 上。
================================================ =======================
在 Python ≥ 3.5 上,使用pathlib.Path.mkdir:
from pathlib import Path
Path("/my/directory").mkdir(parents=True, exist_ok=True)
对于旧版本的 Python,我看到两个质量很好的答案,每个都有一个小缺陷,所以我会给出我的看法:
尝试os.path.exists,并考虑使用os.makedirs 进行创建。
import os
if not os.path.exists(directory):
os.makedirs(directory)
如 cmets 和其他地方所述,存在竞争条件 - 如果在 os.path.exists 和 os.makedirs 调用之间创建目录,则 os.makedirs 将失败并返回 OSError。不幸的是,一揽子OSError并继续不是万无一失的,因为它会忽略由于其他因素导致的目录创建失败,例如权限不足、磁盘已满等。
一种选择是捕获OSError 并检查嵌入的错误代码(请参阅Is there a cross-platform way of getting information from Python’s OSError):
import os, errno
try:
os.makedirs(directory)
except OSError as e:
if e.errno != errno.EEXIST:
raise
另外,可能还有第二个os.path.exists,但假设另一个人在第一次检查后创建了目录,然后在第二次检查之前将其删除——我们仍然可能被愚弄。
根据应用程序,并发操作的危险可能大于或小于文件权限等其他因素带来的危险。在选择实现之前,开发人员必须更多地了解正在开发的特定应用程序及其预期环境。
现代版本的 Python 通过公开 FileExistsError(在 3.3+ 中)对这段代码进行了相当大的改进...
try:
os.makedirs("path/to/directory")
except FileExistsError:
# directory already exists
pass
...并允许a keyword argument to os.makedirs called exist_ok(在 3.2+ 中)。
os.makedirs("path/to/directory", exist_ok=True) # succeeds even if directory exists.