File "/usr/lib/python3.1/codecs.py", line 300, in decode
(result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf8' codec can't decode byte 0x92 in position 805: invalid start byte
你好,我得到这个异常。我如何捕获它,并在遇到此异常时继续读取我的文件。
我的程序有一个循环,它逐行读取文本文件并尝试进行一些处理。但是,我遇到的一些文件可能不是文本文件,或者包含格式不正确的行(外语等)。我想忽略这些行。
以下是无效的
for line in sys.stdin:
if line != "":
try:
matched = re.match(searchstuff, line, re.IGNORECASE)
print (matched)
except UnicodeDecodeError, UnicodeEncodeError:
continue
最佳答案
看http://docs.python.org/py3k/library/codecs.html .当您打开编解码器流时,您可能想要使用附加参数 errors='ignore'
在 Python 3 中,sys.stdin
默认情况下作为文本流打开(参见 http://docs.python.org/py3k/library/sys.html ),并且具有严格的错误检查。
您需要将其重新打开为容错的 utf-8 流。这样的事情会起作用:
sys.stdin = codecs.getreader('utf8')(sys.stdin.detach(), errors='ignore')
关于python - 除了 Python 编解码器错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4554287/