第六章:文件系统-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替换字符,看起来像是一个有黑色背景的菱形,其中包含一个白色的问号。
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值