19

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

for line in open('file','r'):
    decodedLine = line.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

Flimm
  • 136,138
  • 45
  • 251
  • 267
hasmet
  • 758
  • 3
  • 13
  • 32
  • 2
    Yes, strings in Python 3.x no longer have the `decode` method - have a look at https://docs.python.org/3/howto/unicode.html – jonrsharpe Sep 30 '14 at 16:00

5 Answers5

33

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')
Veedrac
  • 58,273
  • 15
  • 112
  • 169
6

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

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
4

After PyJWT 2.0.0 version not having a decode method, so we are getting this error. We should freeze the below version to avoid this issue.

PyJWT==1.7.1
Sathiamoorthy
  • 8,831
  • 9
  • 65
  • 77
1

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)
William Price
  • 4,033
  • 1
  • 35
  • 54
Sarah
  • 1,854
  • 17
  • 18
0

In Python 3, use this mental model:

  • Encoding is the process of converting a str object to a bytes object
  • Decoding is the process of converting a bytes object to a str object

Diagram

You got the error 'str' object has no attribute 'decode'. If you need a str, there is no need to run decode() on it. Access the variable directly without calling decode().

Flimm
  • 136,138
  • 45
  • 251
  • 267