我正在尝试使用以下代码写出一些文本并尽可能将其编码为 utf-8:
outf.write((lang_name + "," + (script_name or "") + "\n").encode("utf-8", errors='replace'))
我收到以下错误:
File "C:\Python27\lib\encodings\cp1252.py", line 15, in decode
return codecs.charmap_decode(input,errors,decoding_table)
UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 6: character maps to <undefined>
我认为errors='replace'
我的编码调用部分会处理这个问题?
fwiw,我只是打开文件
outf = open(outfile, 'w')
没有明确声明编码。
print repr(outf)
产生:
<open file 'myfile.csv', mode 'w' at 0x000000000315E930>
我将 write 语句分离为单独的串联、编码和文件写入:
outstr = lang_name + "," + (script_name or "") + "\n"
encoded_outstr = outstr.encode("utf-8", errors='replace')
outf.write(encoded_outstr)
引发异常的是串联。
字符串是,通过print repr(foo)
lang_name: 'G\xc4\x81ndh\xc4\x81r\xc4\xab'
script_name: u'Kharo\u1e63\u1e6dh\u012b'
进一步的侦探工作表明,我可以毫无困难地将其中任何一个与普通的 ascii 字符串连接起来——它将它们都放入同一个字符串中,这会破坏一些东西。