码迷,mamicode.com
首页 > 编程语言 > 详细

Searching for equivalent of FileNotFoundError in Python 2

时间:2017-08-19 18:46:51      阅读:284      评论:0      收藏:0      [点我收藏+]

标签:code   hat   ioerror   tps   careful   wan   select   create   pretty   

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 modulewhich will use the correct values for the run-time platform.

Searching for equivalent of FileNotFoundError in Python 2

标签:code   hat   ioerror   tps   careful   wan   select   create   pretty   

原文地址:http://www.cnblogs.com/hushaojun/p/7397161.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!