关于在Python阅读和写作的文本文件,one of the main Python contributors mentions这对于surrogateescape
Unicode的错误处理程序:“surrogateescape”无法逃避某些字符
[surrogateescape]手柄通过在很少使用的部分搞起数据远解码错误的Unicode代码点空间。编码时,会将那些隐藏的值转换回原始字节序列,但无法正确解码。
然而,当打开一个文件,然后试图写入输出到另一个文件:
input_file = open('someFile.txt', 'r', encoding="ascii", errors="surrogateescape")
output_file = open('anotherFile.txt', 'w')
for line in input_file:
output_file.write(line)
结果:
File "./break-50000.py", line 37, in main
output_file.write(line)
UnicodeEncodeError: 'utf-8' codec can't encode character '\udcc3' in position 3: surrogates not allowed
注意,输入文件不 ASCII 。然而,在它引发一个特定行上的异常之前,它会横跨数百行包含非ASCII字符的行。输出文件必须是是ASCII并且丢失一些字符就好了。
这是当为UTF-8解码的抛出该错误的行:
“的Zoë\的咖啡屋”
这是十六进制编码:
$ cat z.txt | hd
00000000 27 5a 6f c3 ab 5c 27 73 20 43 6f 66 66 65 65 20 |'Zo..\'s Coffee |
00000010 48 6f 75 73 65 27 0a |House'.|
00000017
为什么surrogateescape
Unicode错误处理程序返回的字符是而不是 ASCII码?这是在Kubuntu Linux 12.10上的Python 3.2.3。
你是否在你的python文件的头文件中指定了编码?只是一个快速检查。 –
@DylanLawrence:这与代码处理的数据完全无关。 –
@DylanLawrence:1)这是Python 3,所以没有必要。 2)这与读取数据有关,而不是Python文件本身的编码。 – dotancohen