在 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:[错误 5] 访问被拒绝:'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
什么时候给出这样的访问错误?有更好的解决方案吗?
最佳答案
你应该使用 OSError 和 IOError。参见 this回答,你会使用类似的东西:
def make_directory_if_not_exists(path):
try:
os.makedirs(path)
except (IOError, OSError) as exception:
if exception.errno != errno.EEXIST:
...
关于python:为什么os.makedirs会导致WindowsError?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17619079/