在Python 2中搜索等效的FileNotFoundError

时间:2014-01-26 18:17:18

标签: python python-3.x python-2.7 file exception-handling

我创建了一个名为Options的类。它工作正常,但不是没有Python 2。 我希望它能同时适用于Python 2和3。 确定了问题:Python 2中不存在FileNotFoundError。 但是,如果我使用IOError,它在Python 3中不起作用

版本3.3中已更改:EnvironmentError,IOError,WindowsError,VMSError,socket.error,select.error和mmap.error已合并到OSError中。

我该怎么办?(请不要讨论我对便携性的选择,我有理由。)

这是代码:

#!/usr/bin/python
#-*-coding:utf-8*

#option_controller.py

#Walle Cyril
#25/01/2014

import json
import os

class Options():
    """Options is a class designed to read, add and change informations in a JSON file with a dictionnary in it.

    The entire object works even if the file is missing since it re-creates it.
    If present it must respect the JSON format: e.g. keys must be strings and so on.
    If something corrupted the file, just destroy the file or call read_file method to remake it."""

    def __init__(self,directory_name="Cache",file_name="options.json",imported_default_values=None):
        #json file
        self.option_file_path=os.path.join(directory_name,file_name)
        self.directory_name=directory_name
        self.file_name=file_name
        #self.parameters_json_file={'sort_keys':True, 'indent':4, 'separators':(',',':')}
        #the default data
        if imported_default_values is None:
            DEFAULT_INDENT = 2
            self.default_values={\
                "translate_html_level": 1,\
                "indent_size":DEFAULT_INDENT,\
                "document_title":"Titre"}
        else:
            self.default_values=imported_default_values


    def read_file(self,read_this_key_only=False):
        """returns the value for the given key or a dictionary if the key is not given.

        returns None if it s impossible"""
        try:
            text_in_file=open(self.option_file_path,'r').read()
        except FileNotFoundError:#not 2.X compatible
            text_in_file=""#if the file is not there we re-make one with default values
        if text_in_file=="":#same if the file is empty
            self.__insert_all_default_values()
            text_in_file=open(self.option_file_path,'r').read()

        try:
            option_dict=json.loads(text_in_file)
        except ValueError:
            #if the json file is broken we re-make one with default values
            self.__insert_all_default_values()
            text_in_file=open(self.option_file_path,'r').read()
            option_dict=json.loads(text_in_file)

        if read_this_key_only:
            if read_this_key_only in option_dict:
                return option_dict[read_this_key_only]#
            else:
                #if the value is not there it should be written for the next time
                if read_this_key_only in self.default_values:
                    self.add_option_to_file(read_this_key_only,self.default_values[read_this_key_only])
                    return self.default_values[read_this_key_only]
                else:
                    #impossible because there is not default value so the value isn t meant to be here
                    return None
        else:
            return option_dict

    def add_option_to_file(self,key,value):#or update
        """Adds or updates an option(key and value) to the json file if the option exists in the default_values of the object."""

        option_dict=self.read_file()
        if key in self.default_values:
            option_dict[key]=value
        open(self.option_file_path,'w').write(\
            json.dumps(option_dict,sort_keys=True, indent=4, separators=(',',':')))


    def __insert_all_default_values(self):
        """Recreate json file with default values.

    called if the document is empty or non-existing or corrupted."""
        try:
            open(self.option_file_path,'w').write(\
            json.dumps(self.default_values,sort_keys=True, indent=4, separators=(',',':')))
        except FileNotFoundError:
            os.mkdir(self.directory_name)#Create the directory
            if os.path.isdir(self.directory_name):#succes
                self.__insert_all_default_values()
            else:
                print("Impossible to write in %s and file %s not found" % (os.getcwd(),self.option_file_path))


#demo
if __name__ == '__main__':

    option_file_object=Options()
    print(option_file_object.__doc__)
    print(option_file_object.read_file())
    option_file_object.add_option_to_file("","test")#this should have no effect

    option_file_object.add_option_to_file("translate_html_level","0")#this should have an effect
    print("value of translate_html_level:",option_file_object.read_file("translate_html_level"))
    print(option_file_object.read_file())

4 个答案:

答案 0 :(得分:40)

如果FileNotFoundError不存在,请定义它:

try:
    FileNotFoundError
except NameError:
    FileNotFoundError = IOError

现在你可以在Python 2中捕获FileNotFoundError,因为它真的是IOError

但要小心,IOError还有其他含义。特别是,任何消息都应该说“文件无法读取”而不是“找不到文件”。

答案 1 :(得分:22)

您可以使用基类异常EnvironmentError并使用'errno'属性来确定引发了哪个异常:

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))  

或者以同样的方式使用IOError:

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

适用于Python 2或Python 3.

注意不要直接与数字值进行比较,因为它们can be different位于不同平台上。相反,使用Python's standard library errno module中的命名常量,它将使用运行时平台的正确值。

答案 2 :(得分:2)

就其价值而言,尽管this answer中几乎没有提到Remove-Item,甚至没有出现在Python 3's official document中,但它仍然存在,并且它是{的父类Python 3中的{1}}。请参见rd /s给您[System.IO.Directory]::Delete()。因此,您可以从技术上以这种方式编写代码,该代码适用于Python 2和Python 3。

IOError

在许多情况下,它可能“足够好”。尽管一般而言,建议不要依赖未记录的行为。因此,我并不是真的建议这种方法。我个人使用its official Exception hierarchy

答案 3 :(得分:1)

FileNotFoundError外,Python 2/3兼容的方式是这样的:

import errno

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

其他答案也很接近,但是如果错误编号不匹配,请不要重新提出。

在大多数情况下,使用IOError很好,但出于某些原因,os.listdir()和朋友在Python 2上举起了OSError,因为IOError继承自OSError只需始终捕获OSError并检查错误号就可以了。