【问题标题】:Why does Python3 get a UnicodeDecodeError reading a text file where Python2 does not?为什么 Python3 在读取 Python2 没有的文本文件时会出现 UnicodeDecodeError?
【发布时间】:2018-03-01 08:45:15
【问题描述】:

我正在阅读一个文本文件。我一直用 python2 做得很好,但我决定用 python3 来运行我的代码。

我读取文本文件的代码是:

neg_words = []
with open('negative-words.txt', 'r') as f:
    for word in f:
        neg_words.append(word)

当我在 python 3 上运行此代码时,出现以下错误:

UnicodeDecodeError                        Traceback (most recent call last)
<ipython-input-14-1e2ff142b4c1> in <module>()
      3 pos_words = []
      4 with open('negative-words.txt', 'r') as f:
----> 5     for word in f:
      6         neg_words.append(word)
      7 with open('positive-words.txt', 'r') as f:

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/codecs.py in 
decode(self, input, final)
    319         # decode input (taking the buffer into account)
    320         data = self.buffer + input
--> 321         (result, consumed) = self._buffer_decode(data, self.errors, final)
    322         # keep undecoded input until the next call
    323         self.buffer = data[consumed:]

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xef in position 3988: invalid continuation byte

在我看来,python2 可以毫无问题地解码某种形式的文本,而 python3 却不能。

谁能解释一下python2和python3在这个错误方面的区别。为什么它出现在一个版本中而不出现在另一个版本中?我怎样才能阻止它?

【问题讨论】:

  • 因为 Python 2 读取字节,并且不会尝试将字节解码为 Unicode 文本对象。

标签: python python-3.x unicode


【解决方案1】:

您的文件不是 UTF-8 编码的。找出使用什么编码,并在打开文件时明确说明:

with open('negative-words.txt', 'r', encoding="<correct codec>") as f:

在 Python 2 中,str 是一个二进制字符串,包含编码数据,而不是 Unicode 文本。如果您使用import io 然后io.open(),您会遇到同样的问题,或者如果您尝试解码使用word.decode('utf8') 读取的数据。

您可能想了解 Unicode 和 Python。我强烈推荐 Ned Batchelder 的 Pragmatic Unicode

【讨论】:

    【解决方案2】:

    或者我们可以简单地在二进制模式下读取文件:

     with open(filename, 'rb') as f:
         pass
    

    'r'打开读取(默认)

    'b'二进制模式

    【讨论】:

      猜你喜欢
      • 2020-05-27
      • 2020-10-07
      • 2018-12-26
      • 2018-11-12
      • 1970-01-01
      • 2019-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多