gpt4 book ai didi

python - FileNotFoundError "try .. except IOError"未捕获时如何处理?

转载 作者:IT老高 更新时间:2023-10-28 21:10:01 24 4
gpt4 key购买 nike

如何在 python 3 上发现错误?我用谷歌搜索了很多,但似乎没有一个答案有效。文件 open.txt 不存在,所以它应该打印 e.errno。

这是我现在尝试的:

这是我定义的函数

try:
with open(file, 'r') as file:
file = file.read()
return file.encode('UTF-8')
except OSError as e:
print(e.errno)

但是当我得到这个错误时我没有打印任何东西

FileNotFoundError: [Errno 2] No such file or directory: 'test.txt'

最佳答案

FileNotFoundErrorOSError 的子类,捕获它或异常本身:

except OSError as e:

操作系统异常已在 Python 3.3 中重新设计; IOError 已合并到 OSError。见 PEP 3151: Reworking the OS and IO exception hierarchy section在 What's New 文档中。

更多详情,OS Exceptions section如需更多信息,请向下滚动查看类层次结构。

也就是说,您的代码应该仍然可以工作,因为 IOError 现在是 OSError 的别名:

>>> IOError
<class 'OSError'>

确保您将异常处理程序放置在正确的位置。仔细查看异常的回溯,以确保您没有错过实际引发的位置。最后但同样重要的是,您确实重新启动了 Python 脚本,对吧?

关于python - FileNotFoundError "try .. except IOError"未捕获时如何处理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28633555/

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