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
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.
‘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.
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!
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')
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'.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With