'str' object has no attribute 'decode' in Python3

狂风中的少年 提交于 2019-11-26 21:19:02

问题


I've some problem with "decode" method in python 3.3.4. This is my code:

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

But I can't decode the line for this problem:

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

Do you have any ideas? Thanks


回答1:


One encodes strings, and one decodes bytes.

You should read bytes from the file and decode them:

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

Luckily open has an encoding argument which makes this easy:

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



回答2:


open already decodes to Unicode in Python 3 if you open in text mode. If you want to open it as bytes, so that you can then decode, you need to open with mode 'rb'.




回答3:


This works for me smoothly to read Chinese text in Python 3.6. First, convert str to bytes, and then decode them.

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


来源:https://stackoverflow.com/questions/26125141/str-object-has-no-attribute-decode-in-python3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!