aazzsx
V2EX  ›  问与答

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

  •  
  •   aazzsx · Nov 19, 2014 · 6058 views
    This topic created in 4192 days ago, the information mentioned may be changed or developed.
    在python2打开一个不存在的文件是 IOError
    在3就是 FileNotFoundError?
    可是 《Head First Python》 上写的是 IOError
    我用的是 3.4
    书上写的 3.1
    5 replies    2014-11-19 12:23:20 +08:00
    yakczh
        1
    yakczh  
       Nov 19, 2014
    python3 用 open(file,mod='r',encodineg='utf8') 打开一个非utf8编码的文件,会报异常,利用这一点,可以识别出utf8编码的文件
    aazzsx
        2
    aazzsx  
    OP
       Nov 19, 2014
    @yakczh 好像不是一个问题……python3在shell打开一个不存在的文件时弹出 FileNotFoundError 而在 .py文件里面可以用IOError捉到错误,用FileNotFoundError出错没有定义?
    staticor
        3
    staticor  
       Nov 19, 2014
    应该是对异常类的重新细分吧, 在3.2-3.4版本更新中就有些变化 3.1不清楚是怎么分的.

    可参考http://devdocs.io/python/library/exceptions#IOError
    gateswong
        4
    gateswong  
       Nov 19, 2014
    python 3.2之后把IOError 替换成了FileNotFoundError
    gateswong
        5
    gateswong  
       Nov 19, 2014
    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里没有这个异常
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1167 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 76ms · UTC 17:39 · PVG 01:39 · LAX 10:39 · JFK 13:39
    ♥ Do have faith in what you're doing.