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

问题描述 投票:0回答:5

我在 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'

你有什么想法吗?谢谢

python python-3.x python-3.3
5个回答
32
投票

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

您应该从文件中读取字节并解码它们:

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

6
投票
如果您在文本模式下打开,

open
已经在 Python 3 中解码为 Unicode。如果您想将其作为字节打开,以便可以解码,则需要以“rb”模式打开。


4
投票

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

PyJWT==1.7.1

1
投票

这可以让我在Python 3.6中顺利阅读中文文本。首先,将 str 转换为 bytes,然后对其进行解码。

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

0
投票

在 Python 3 中,使用以下思维模型:

  • 编码是将
    str
    对象转换为
    bytes
    对象
  • 的过程
  • 解码是将
    bytes
    对象转换为
    str
    对象
  • 的过程

您收到错误

'str' object has no attribute 'decode'
。如果您需要
str
,则无需在其上运行
decode()
。直接访问变量,无需调用
decode()

© www.soinside.com 2019 - 2024. All rights reserved.