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

hasmet picture hasmet · Sep 30, 2014 · Viewed 68.8k times · Source

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

Answer

Veedrac picture Veedrac · Sep 30, 2014

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