我已经把ubuntu从14.04(python 3.4.3)升级到16.04(python3.5.2)。现在,我的脚本无法读取编码为cp1251的文件:
with open(fs[0], encoding='cp1251') as f:
lines = f.readlines()
f.close()
它给出一个错误:
Traceback (most recent call last):
File "/home/michael/PycharmProjects/Rad/get_info.py", line 9, in <module>
r.get_tests()
File "/home/michael/PycharmProjects/Rad/rad.py", line 166, in get_tests
s = f.readlines()
File "/usr/lib/python3.5/encodings/cp1251.py", line 23, in decode
return codecs.charmap_decode(input,self.errors,decoding_table)[0]
UnicodeDecodeError: 'charmap' codec can't decode byte 0x98 in position 13: character maps to <undefined>
Process finished with exit code 1
调试会导致文件中出现以下代码:
class IncrementalDecoder(codecs.IncrementalDecoder):
def decode(self, input, final=False):
return codecs.charmap_decode(input,self.errors,decoding_table)[0]
在这个python版本中发生了什么变化以及如何避免这个错误?
最佳答案
所以我找到了a way来修复这个在python 2和3中都有效的错误:
import codecs
...........
with codecs.open(fs[0], encoding='cp1251', errors='replace') as f:
lines = f.readlines()
f.close()