【发布时间】:2015-04-22 09:38:58
【问题描述】:
如何在 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'
【问题讨论】:
-
不相关:不要在相同的上下文中为不同的目的使用相同的名称。请改用
text = file.read()。保持文本为 Unicode,除非绝对必要,否则不要将其编码为字节。 -
确保运行正确的文件。提供完整的回溯。
标签: python exception python-3.x try-catch