'str'对象在Python3中没有属性'decode'

时间:2014-09-30 15:57:58

标签: python

我在"解码"中遇到了一些问题。 python 3.3.4中的方法。这是我的代码:

for lines in open('file','r'):
    decodedLine = lines.decode('ISO-8859-1')
    line = decodedLine.split('\t')

但我无法解决这个问题:

AttributeError: 'str' object has no attribute 'decode'

你有什么想法吗?感谢

4 个答案:

答案 0 :(得分:20)

一个编码字符串,一个解码字节。

您应该从文件中读取字节并对其进行解码:

for lines in open('file','rb'):
    decodedLine = lines.decode('ISO-8859-1')
    line = decodedLine.split('\t')

幸运的是open有一个编码参数,这使得这很简单:

for decodedLine in open('file', 'r', encoding='ISO-8859-1'):
    line = decodedLine.split('\t')

答案 1 :(得分:1)

如果在文本模式下打开,

open已经在Python 3中解码为Unicode。如果你想打开它作为字节,以便你可以解码,你需要打开模式' rb'。

答案 2 :(得分:1)

这对我来说非常适合在Python 3.6中阅读中文文本。首先,将str转换为字节,然后解码它们。

for l in open('chinese2.txt','rb'):
    decodedLine = l.decode('gb2312')
    print(decodedLine)

答案 3 :(得分:1)

PyJWT 2.0.0 版本之后没有 decode 方法,因此我们收到此错误。我们应该冻结以下版本以避免此问题。

PyJWT==1.7.1