gpt4 book ai didi

python:为什么os.makedirs会导致WindowsError?

转载 作者:太空狗 更新时间:2023-10-29 21:01:19 24 4
gpt4 key购买 nike

在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com