【发布时间】: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