我有一个 UTF-16 LE 锉 BOM. 我想把这个文件翻转成没有BOM的UTF-8格式,这样我就可以用Python来解析它。
我通常使用的代码没有起到作用,它返回的是未知字符而不是实际的文件内容。
f = open('dbo.chrRaces.Table.sql').read()
f = str(f).decode('utf-16le', errors='ignore').encode('utf8')
print f
正确的解码方式是什么,这样我就可以使用 f.readlines()
?
首先,你应该在二进制模式下读取,否则事情会变得混乱。
然后,检查并删除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字符串来完成所有这些工作。
另外。errors='ignore'
关于 decode
可能是个坏主意。考虑一下哪种情况更糟糕:让你的程序告诉你一些事情是错误的并停止,或者返回错误的数据?
这在 Python 3 中是可行的。
f = open('test_utf16.txt', mode='r', encoding='utf-16le').read()
print(f)