我正在开发一个必须能够打开UTF-8和UTF-16编码文件的Python工具.在Python 3.2中,我使用以下代码尝试使用UTF-8打开文件,然后如果出现unicode错误则尝试使用UTF-16:
def readGridFromPath(self, filepath):
    try:
        self.readGridFromFile(open(filepath,'r',encoding='utf-8'))
    except UnicodeDecodeError:
            self.readGridFromFile(open(filepath,'r',encoding='utf-16'))
(readGridFromFile将要么完成,要么提出一个UnicodeDecodeError.)
但是,当我在Python 2.x中运行此代码时,我得到:
TypeError: 'encoding' is an invalid keyword argument for this function
我在文档中看到Python 2.x open()没有encoding关键字.有什么方法可以让我使我的代码Python 2.x兼容吗?
tor*_*gen 21
io.open 是您的需求的替代品,因此您提供的代码示例在Python 2.x中将如下所示:
import io
def readGridFromPath(self, filepath):
    try:
        self.readGridFromFile(io.open(filepath, 'r', encoding='utf-8'))
    except UnicodeDecodeError:
        self.readGridFromFile(io.open(filepath, 'r', encoding='utf-16'))
io.open被描述在这里详细说明.它的原型是:
io.open(file,mode ='r',buffering = -1,encoding = None,errors = None,newline = None,closefd = True)
io 模块本身被设计为Python 2.x和Python 3.x之间的兼容层,以便于过渡到Py3k并简化现有Python 2.x代码的后端移植和维护.
此外,请注意可能有一个警告使用codecs.open,因为它只在二进制模式下工作:
注意:即使未指定二进制模式,也始终以二进制模式打开文件.这样做是为了避免因使用8位值进行编码而导致数据丢失.这意味着在读写时不会自动转换'\n'.
此外,您可能会遇到手动检测和剥离UTF8 BOM的问题 - codecs.open将UTF8 BOM内联为u'\ufeff'字符.