Python3 打开文件错误不一样了?

2014-11-19 11:25:10 +08:00
 aazzsx
在python2打开一个不存在的文件是 IOError
在3就是 FileNotFoundError?
可是 《Head First Python》 上写的是 IOError
我用的是 3.4
书上写的 3.1
5218 次点击
所在节点    问与答
5 条回复
yakczh
2014-11-19 11:46:06 +08:00
python3 用 open(file,mod='r',encodineg='utf8') 打开一个非utf8编码的文件,会报异常,利用这一点,可以识别出utf8编码的文件
aazzsx
2014-11-19 11:58:40 +08:00
@yakczh 好像不是一个问题……python3在shell打开一个不存在的文件时弹出 FileNotFoundError 而在 .py文件里面可以用IOError捉到错误,用FileNotFoundError出错没有定义?
staticor
2014-11-19 12:06:45 +08:00
应该是对异常类的重新细分吧, 在3.2-3.4版本更新中就有些变化 3.1不清楚是怎么分的.

可参考http://devdocs.io/python/library/exceptions#IOError
gateswong
2014-11-19 12:18:42 +08:00
python 3.2之后把IOError 替换成了FileNotFoundError
gateswong
2014-11-19 12:23:20 +08:00
https://docs.python.org/3.2/library/functions.html#open

> Open file and return a corresponding file object. If the file cannot be opened, an IOError is raised.

https://docs.python.org/3.3/library/functions.html#open

> Open file and return a corresponding file object. If the file cannot be opened, an OSError is raised.

https://docs.python.org/3.3/library/exceptions.html#FileNotFoundError

> exception FileNotFoundError
> Raised when a file or directory is requested but doesn’t exist. Corresponds to errno ENOENT.

3.2里没有这个异常

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/147679

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX