如何获取UnicodeDecodeError出现位置的位置?
我在here找到了材料,并试图在下面实施。但我收到错误NameError: name 'err' is not defined
我已经在互联网上搜索过StackOverflow,但是找不到任何提示如何使用它。在python文档中,它说这个特殊的异常具有start属性,所以它必须是可能的。
谢谢。
data = buffer + data
try:
data = data.decode("utf-8")
except UnicodeDecodeError:
#identify where did the error occure?
#chunk that piece off -> copy troubled piece into buffer and
#decode the good one -> then go back, receive the next chunk of
#data and concatenate it to the buffer.
buffer = err.data[err.start:]
data = data[0:err.start]
data = data.decode("utf-8")
答案 0 :(得分:4)
该信息存储在异常中。您可以使用as
关键字获取异常对象,并使用start
属性:
while True:
try:
data = data.decode("utf-8")
except UnicodeDecodeError as e:
data = data[:e.start] + data[e.end:]
else:
break
答案 1 :(得分:1)
如果你只是想忽略错误并解码其余的错误,你可以这样做:
.env