您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

在Python 2中搜索FileNotFoundError的等效项

在Python 2中搜索FileNotFoundError的等效项

您可以使用基类异常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模块中使用命名的常量,该常量将为运行时平台使用正确的值。

python 2022/1/1 18:44:27 有300人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶