Searching for equivalent of FileNotFoundError in Python 2

前端 未结 4 698
鱼传尺愫
鱼传尺愫 2020-12-28 12:17

I created a class named Options. It works fine but not not with Python 2. And I want it to work on both Python 2 and 3. The problem is identified: FileNotFoundError doesn t

4条回答
  •  难免孤独
    2020-12-28 13:05

    The Python 2 / 3 compatible way to except a FileNotFoundError is this:

    import errno
    
    try:
        with open('some_file_that_does_not_exist', 'r'):
            pass
    except EnvironmentError as e:
        if e.errno != errno.ENOENT:
            raise
    

    Other answers are close, but don't re-raise if the error number doesn't match.

    Using IOError is fine for most cases, but for some reason os.listdir() and friends raise OSError instead on Python 2. Since IOError inherits from OSError it's fine to just always catch OSError and check the error number.

    Edit: The previous sentence is only true on Python 3. To be cross compatible, instead catch EnvironmentError and check the error number.

提交回复
热议问题