【发布时间】:2013-07-12 16:00:01
【问题描述】:
在python中,如果不存在,我已经创建了一个创建目录的函数。
def make_directory_if_not_exists(path):
try:
os.makedirs(path)
break
except OSError as exception:
if exception.errno != errno.EEXIST:
raise
在 Windows 上,有时我会得到以下异常:
WindowsError: [Error 5] Access is denied: 'C:\\...\\my_path'
在 Windows 文件浏览器中打开目录时似乎会发生这种情况,但我无法可靠地重现它。所以我只是做了以下解决方法。
def make_directory_if_not_exists(path):
while not os.path.isdir(path):
try:
os.makedirs(path)
break
except OSError as exception:
if exception.errno != errno.EEXIST:
raise
except WindowsError:
print "got WindowsError"
pass
这里发生了什么,即 Windows mkdir 何时给出这样的访问错误?有没有更好的解决方案?
【问题讨论】:
-
来自docs:
Raises an error exception if the leaf directory already exists or cannot be created. -
@AshwiniChaudhary,我知道。我已经用
except OSError捕捉到了这个异常。我在问WindowsError。