Python's “open()” throws different errors for “file not found” - how to handle both exceptions?

一笑奈何 提交于 2019-11-27 19:16:34

In 3.3, IOError became an alias for OSError, and FileNotFoundError is a subclass of OSError. So you might try

except (OSError, IOError) as e:
   ...

This will cast a pretty wide net, and you can't assume that the exception is "file not found" without inspecting e.errno, but it may cover your use case.

PEP 3151 discusses the rationale for the change in detail.

This strikes me as better than a simple except:, but I'm not sure if it is the best solution:

error_to_catch = getattr(__builtins__,'FileNotFoundError', IOError)

try:
    f = open('.....')
except error_to_catch:
    print('!')

So to exactly catch only when a file is not found, I do:

import errno
try:
   open(filename, 'r')
except (OSError, IOError) as e: # FileNotFoundError does not exist on Python < 3.3
   if getattr(e, 'errno', 0) == errno.ENOENT:
      ... # file not found
   raise
dm03514

you can catch 2 errors at the same time

except (FileNotFoundError, IOError):

I didn't realize that is what you were asking. I hope there is a more eloquent solution then to manually inspect

try:
   error_to_catch = FileNotFoundError
except NameError:
   error_to_catch = IOError

except error_to_catch

cwallenpoole does this conditional more eloquently in his answer (error_to_catch = getattr(__builtins__,'FileNotFoundError', IOError))

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!