python - UnicodeDecodeError 异常是如何工作的?
问题描述
如果我使用无效 utf-8 字符的文件(我将此页面保存为 file.txt:https ://www.w3.org/2001/06/utf-8-test/UTF-8-demo.html )并尝试检查此文件中的每一行是否包含有效的 utf8(如果不是,则应忽略此行)我收到错误消息:
文件“test.py”,第 13 行,用于文件中的行:文件“C:\Users\user\AppData\Local\Programs\Python\Python38\lib\encodings\cp1252.py”,第 23 行,解码返回codecs.charmap_decode(input,self.errors,decoding_table)[0] UnicodeDecodeError: 'charmap' codec can't decode byte 0x90 in position 240: character maps to undefined
编码:
file = open("file.txt", "r")
for line in file:
line = line.strip()
try:
print(line)
except UnicodeDecodeError:
print("UnicodeDecodeError " + line)
pass
except-line & pass 是否应该确保如果发生 UnicodeDecodeError,它将被忽略并且脚本继续下一行?
解决方案
读取行时引发异常,这发生在for
迭代器中。您需要将读取的行封装到异常处理块中,为此您需要比提供的隐式迭代器更多的手动处理for
:
with open('file.txt', 'r', encoding='utf-8') as fh:
while True:
try:
line = fh.readline()
except UnicodeDecodeError:
print('error') # line is obviously not available to output here, since it failed to decode
continue
if not line:
break # end the loop when the file is at its end
print(line)
请注意,我不确定这对损坏的文件实际上如何表现,甚至在遇到损坏的字节后是否可以继续阅读。如果这不起作用,您将需要更多手动操作并以'rb'
模式打开文件以获取 raw bytes
,然后手动尝试.decode('utf-8')
. 这种方法还允许您将无法解码的行输出为原始字节,根据定义,在将文件作为文本读取时这是不可能的。
推荐阅读
- javascript - 如何在 _document.js 和 Next.js 上的页面之间共享 React 上下文?
- python - 根据 Python 中两行之间的匹配创建一个具有 [0,1] 的新列
- java - Java WSS 连接无法创建传输异常
- php - 在php上的多维数组中获取特定数组
- docker - Sed 变量替换在 dockerfile 中不起作用
- azure - Azure DevOps az cli 从管道以用户身份登录
- amazon-web-services - 我正在尝试使用 aws cli 标记我的 AWS 粘合作业,其中键名是“My key”,值是“job1”,键名将是“My key”
- swift - 存在 NavigationView 时,SwiftUI macOS 无法更改主菜单
- react-native - 反应本机密码显示隐藏
- python - python ABC & 多重继承