V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
aazzsx
V2EX  ›  问与答

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

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

    可参考http://devdocs.io/python/library/exceptions#IOError
    gateswong
        4
    gateswong  
       2014-11-19 12:18:42 +08:00
    python 3.2之后把IOError 替换成了FileNotFoundError
    gateswong
        5
    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里没有这个异常
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3045 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 14:54 · PVG 22:54 · LAX 07:54 · JFK 10:54
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.