您可以使用基类异常EnvironmentError并使用’errno’属性来确定引发了哪个异常:
from __future__ import print_function
import os
import errno
try:
open('no file of this name') # generate 'file not found error'
except EnvironmentError as e: # OSError or IOError...
print(os.strerror(e.errno))
或者只是以相同的方式使用IOError:
try:
open('/Users/test/Documents/test') # will be a permission error
except IOError as e:
print(os.strerror(e.errno))
适用于Python 2或Python 3。
注意不要直接与数字值进行比较,因为它们在不同平台上可能会有所不同。相反,请在Python的标准库errno
模块中使用命名的常量,该常量将为运行时平台使用正确的值。