首先,您应该以二进制模式阅读,否则会令事情变得混淆。
然后,请检查并删除BOM,因为它是文件的一部分,但不属于实际文本。
import codecs
encoded_text = open('dbo.chrRaces.Table.sql', 'rb').read() #you should read in binary mode to get the BOM correctly
bom = codecs.BOM_UTF16_LE #print dir(codecs) for other encodings
assert encoded_text.startswith(bom) #make sure the encoding is what you expect, otherwise you'll get wrong data
encoded_text = encoded_text[len(bom):] #strip away the BOM
decoded_text = encoded_text.decode('utf-16le') #decode to unicode
在完成所有解析/处理之前,请不要进行编码(如转换为utf-8
或其他编码)。您应该使用unicode字符串进行所有操作。
此外,在decode
时使用errors='ignore'
可能是一个坏主意。考虑哪个更糟:让程序提示错误并停止,还是返回错误的数据?
这在 Python 3 中有效:
f = open('test_utf16.txt', mode='r', encoding='utf-16').read()
print(f)
utf-16
编码,虽然没有官方文档支持,但 utf-16
编码好像可以自动处理 BOM。如果你使用 utf-16le
编码,它仍然能够工作,但是 BOM 会保留在那里,你可以通过使用字符串函数和 codecs.BOM_UTF16_BE
来手动去除它。 - mgrandi