1. 問題發現:
出現:讀取文件,對其進行解碼,出現錯誤,AttributeError: 'str' object has no attribute 'decode'
解釋:屬性錯誤,str對象不包含‘decode’屬性。
2.原因解釋:
出現問題原因:str與bytes表示的是兩種數據類型,str為字符串型,bytes為字節型。對str編碼encode得到bytes,
對bytes解碼得到str,兩者互為轉換。而上面出現問題的原因是對str字符串使用了解碼,顯然是豬頭不對馬尾。
3.解決方法:
解決辦法:刪除decode(‘utf-8’)
4.代碼演示:
txt = '你好,shiyi,很感謝你陪伴我的日子' #str->bytes encode txt = txt.encode('utf-8') print(type(txt)) #bytes->str decode txt = txt.decode('utf-8') print(type(txt))
5.結果展示:
<class 'bytes'> <class 'str'> Process finished with exit code 0