Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
305 views
in Technique[技术] by (71.8m points)

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

But I can't decode the line for this problem:

AttributeError: 'str' object has no attribute 'decode'

Do you have any ideas? Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

Luckily open has an encoding argument which makes this easy:

for decodedLine in open('file', 'r', encoding='ISO-8859-1'):
    line = decodedLine.split('')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...