Python编解码器错误除外?

时间:2010-12-29 12:57:15

标签: python decode encode

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

1 个答案:

答案 0 :(得分:6)

看看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')