Searching for equivalent of FileNotFoundError in Python 2

前端 未结 4 688
鱼传尺愫
鱼传尺愫 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

    You can use the base class exception EnvironmentError and use the 'errno' attribute to figure out which exception was raised:

    from __future__ import print_function
    
    import os
    import errno
    
    try:
        open('no file of this name')   # generate 'file not found error'
    except EnvironmentError as e:      # OSError or IOError...
        print(os.strerror(e.errno))  
    

    Or just use IOError in the same way:

    try:
        open('/Users/test/Documents/test')   # will be a permission error
    except IOError as e:
        print(os.strerror(e.errno))  
    

    That works on Python 2 or Python 3.

    Be careful not to compare against number values directly, because they can be different on different platforms. Instead, use the named constants in Python's standard library errno module which will use the correct values for the run-time platform.

提交回复
热议问题