第六章:文件系统-codecs:字符串编码和解码-错误处理-解码错误

6.10.4.2 解码错误
数据解码时也有可能遇到错误,特别是如果使用了错误的编码。

import codecs
import sys

from codecs_to_hex import to_hex

error_handling = sys.argv[1]

text = 'fráncais'
print('Original      :',repr(text))

# Save the data with one encoding.
with codecs.open('decode_error.txt','w',
                 encoding='utf-16') as f:
    f.write(text)

# Dump the bytes from the file.
with open('decode_error.txt','rb') as f:
    print('File contents:',to_hex(f.read(),1))

# Try to read data with the wrong encoding
with codecs.open('decode_error.txt','r',
                 encoding='utf-8',
                 errors=error_handling) as f:
    try:
        data = f.read()
    except UnicodeDecodeError as err:
        print('ERROR:',err)
    else:
        print('Read       :',repr(data))

与编码一样,如果不能正确地解码字节流,则strict错误处理模式会产生一个异常。在这里,产生UnicodeDecodeError的原因是尝试使用UTF-8解码器将UTF-16 BOM部分转换为一个字符。
在这里插入图片描述
切换到ignore会让解码器跳过不合法的字节。不过,结果仍然不是原来期望的结果,因为其中包括嵌入的null字节。
在这里插入图片描述
采用replace模式时,非法的字节会被替换为\uFFFD,这是官方的Unicode替换字符,看起来像是一个有黑色背景的菱形,其中包含一个白色的问号。
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_43193719/article/details/88721427