'Str' object has no 'decode' attribute in Python3
I have a problem with the "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 cannot decode the string for this problem:
AttributeError: 'str' object has no attribute 'decode'
Do you have any ideas? Thanks to
+8
hasmet
source
to share
3 answers
One encodes strings and one decodes bytes.
You have to read the bytes from the file and decode them:
for lines in open('file','rb'):
decodedLine = lines.decode('ISO-8859-1')
line = decodedLine.split('\t')
Fortunately, it open
has an encoding argument that makes this simple:
for decodedLine in open('file', 'r', encoding='ISO-8859-1'):
line = decodedLine.split('\t')
+22
Veedrac
source
to share
open
already decodes Unicode in Python 3 if you open it in text mode. If you want to open it as bytes so that you can decode then you need to open it with 'rb' mode.
+2
Daniel roseman
source
to share
This works smoothly for me to read Chinese text in Python 3.6. First, we convert str to bytes and then decode them.
for l in open('chinese2.txt','rb'):
decodedLine = l.decode('gb2312')
print(decodedLine)
+1
Sarah
source
to share