您的位置:首页 > 编程语言 > Python开发

Searching for equivalent of FileNotFoundError in Python 2

2017-08-19 16:52 471 查看
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 exist in Python 2. But if I use IOError it doesn t work in Python 3

Changed in version 3.3: EnvironmentError, IOError, WindowsError, VMSError, socket.error, select.error and mmap.error have been merged into OSError.

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.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐