关于在Python中读写文本文件,其中一个主要的Python贡献者提到了有关surrogateescapeUnicode错误处理程序的问题:
[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)
Run Code Online (Sandbox Code Playgroud)
结果是:
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
Run Code Online (Sandbox Code Playgroud)
请注意,输入文件不是 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 …Run Code Online (Sandbox Code Playgroud)