我正在尝试读取和处理一个文件。这在Python2.7中运行得非常好,但我无法在Python 3中运行它。
在Python2.7中,它在不提供任何编码的情况下工作,而在Python3中,我尝试了有编码和无编码的所有组合。
经过深入研究,我发现read返回的内容在两个版本中是不同的。
在Python2.7中工作的代码:>>> f = open('resource.cgn', 'r')
>>> content = f.read()
>>> type(content)
>>> content[0:20]
'\x04#lwq \x7f`g \xa0\x03\xa3,ess to'
>>> content[0]
'\x04'
但是在Python 3中:>>> f = open('resource.cgn','r')
>>> content = f.read()
Traceback (most recent call last):
File "", line 1, in
File "/usr/local/lib/python3.6/encodings/ascii.py", line 26, in decode
return codecs.ascii_decode(input, self.errors)[0]
UnicodeDecodeError: 'ascii' codec cant decode byte 0xa0 in p