关于Python≥ 3.5,使用pathlib.Path.mkdir
:
from pathlib import Path
Path("/my/directory").mkdir(parents=True, exist_ok=True)
对于较旧版本的Python,我看到了两个很好的答案,每个答案都有一个小缺陷,因此我将给出我的看法:
try os.path.exists
,并考虑os.makedirs
的创作.
import os
if not os.path.exists(directory):
os.makedirs(directory)
As noted in comments and elsewhere, there's a race condition – if the directory is created between the os.path.exists
and the os.makedirs
calls, the os.makedirs
will fail with an OSError
. Unfortunately, blanket-catching OSError
and continuing is not foolproof, as it will ignore a failure to create the directory due to other factors, such as insufficient permissions, full disk, etc.
一种 Select 是捕获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
Alternatively, there could be a second os.path.exists
, but suppose another created the directory after the first check, then removed it before the second one – we could still be fooled.
根据应用程序的不同,并发操作的危险可能或多或少比其他因素(如文件权限)带来的危险更大或更小.在 Select 实现之前,开发人员必须更多地了解正在开发的特定应用程序及其预期环境.
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.