如何检查要写入文件的目录是否存在,如果不存在,使用 Python 创建目录?
最佳答案
在 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
并检查嵌入的错误代码(参见 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.
关于python - 如何安全地创建嵌套目录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/273192/