向Python 2反向移植(encoding =“utf-8”)
我有一个为Python 3构build的Python代码库,它使用Python 3样式open()和编码参数:
https://github.com/miohtama/vvv/blob/master/vvv/textlineplugin.py#L47
with open(fname, "rt", encoding="utf-8") as f: 现在我想把这个代码支持到Python 2.x,这样我就能拥有一个可以与Python 2和Python 3一起工作的代码库。
 什么是解决open()差异和缺乏编码参数的build议策略? 
 我可以有一个Python 3 open()风格的文件处理程序,它stream动的字节,所以它会像Python 2 open() ? 
1.要在Python 2中获得编码参数:
 如果您只需要支持Python 2.6和2.7,则可以使用io.open而不是open 。  io是Python 3的新io子系统,它也存在于Python 2.6和2.7中。 请注意,在Python 2.6(以及3.0)中,它是纯粹用python实现的,速度很慢,所以如果你需要读取文件的速度,这不是一个好的select。 
 如果您需要速度,或者您需要支持Python 2.5或更早版本,则可以使用codecs.open 。 它也有一个编码参数,和io.open非常相似,除了它处理行尾的不同。 
  2.要得到一个Python 3 open()风格的文件处理程序,它将字节stream: 
 open(filename, 'rb') 
注意'b',意思是'字节'。
我认为
 from io import open 
应该做。
这里有一个方法:
 with open("filename.txt", "rb") as f: contents = f.read().decode("UTF-8") 
这可能有诀窍:
 import sys if sys.version_info[0] > 2: # py3k pass else: # py2 import codecs import warnings def open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None): if newline is not None: warnings.warn('newline is not supported in py2') if not closefd: warnings.warn('closefd is not supported in py2') if opener is not None: warnings.warn('opener is not supported in py2') return codecs.open(filename=file, mode=mode, encoding=encoding, errors=errors, buffering=buffering) 
那么你可以让你的代码以python3的方式。
 请注意,一些API如newline , closefd , opener不起作用