Python - 使用BOM解码UTF-16文件

Dus*_*tin 10 python encoding file utf-8 utf-16

我有一个带BOMUTF-16 LE文件.我想将这个文件翻转到没有BOM的UTF-8,所以我可以用Python解析它.

我使用的常用代码没有做到这一点,它返回了未知字符而不是实际的文件内容.

f = open('dbo.chrRaces.Table.sql').read()
f = str(f).decode('utf-16le', errors='ignore').encode('utf8')
print f
Run Code Online (Sandbox Code Playgroud)

解码此文件的正确方法是什么,以便我可以解析它f.readlines()

gon*_*opp 16

首先,你应该以二进制模式阅读,否则会让人感到困惑.

然后,检查并删除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
Run Code Online (Sandbox Code Playgroud)

utf-8在完成所有解析/处理之前,不要编码(以或其他方式).你应该使用unicode字符串做所有这些.

此外,errors='ignore'decode可能是一个坏主意.考虑更糟糕的事情:让你的程序告诉你一些错误并停止或返回错误的数据?


Ale*_*der 6

这适用于 Python 3:

f  = open('test_utf16.txt', mode='r', encoding='utf-16').read()
print(f)
Run Code Online (Sandbox Code Playgroud)

  • 编辑使其只是“utf-16”,它似乎没有记录,但“utf-16”的编码似乎确实会自动处理 BOM。如果您使用“utf-16le”,它仍然_works_,但 BOM 仍然存在,您可以使用字符串函数和“codecs.BOM_UTF16_BE”自行删除它 (4认同)
  • 如果您仅将编码设置为**utf-16**,则无需手动消除 BOM。 (3认同)