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

后端 未结 3 752
北恋
北恋 2020-12-01 18:59

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


        
3条回答
  •  萌比男神i
    2020-12-01 19:40

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

提交回复
热议问题