Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 581
hasmet Avatar asked Sep 30 '14 15:09

hasmet


People also ask

What is attributeerror ‘STR’ object has no attribute ‘decode’?

What is AttributeError: ‘str’ object has no attribute ‘decode’? In Python 2, a string object is associated with the decode () attribute. The decode () method is mainly used to transform the encoded string back to the original string.

Why do I get Python 3 error ‘STR’?

‘str’ object has no attribute ‘decode’. Python 3 error? You are trying to decode an object that is already decoded. You have a str, there is no need to decode from UTF-8 anymore. As for your fetch () call, you are explicitly asking for just the first message. Use a range if you want to retrieve more messages.

How to remove data from a string in Python?

The solution is simple, simply remove the data = str (data) statement (or remove the decode statement and simply do print (data)) Thanks for contributing an answer to Stack Overflow!


2 Answers

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')
like image 166
Veedrac Avatar answered Sep 30 '22 22:09

Veedrac


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

like image 38
Daniel Roseman Avatar answered Sep 30 '22 23:09

Daniel Roseman