如何解决如何安全地创建嵌套目录?
在 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)
如评论和其他地方所述,存在竞争条件 - 如果在os.path.exists
和os.makedirs
调用之间创建目录,则os.makedirs
将失败并显示OSError
. 不幸的是,一揽子捕获OSError
并继续并不是万无一失的,因为它会忽略由于其他因素导致的目录创建失败,例如权限不足、磁盘已满等。
一种选择是捕获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
…并允许调用关键字参数os.makedirs``exist_ok
(在 3.2+ 中)。
os.makedirs("path/to/directory", exist_ok=True) # succeeds even if directory exists.
解决方法
检查文件要写入的目录是否存在,如果不存在,使用 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)
不知何故,我错过了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)
是否有一个标志open()
,使这自动发生?