Python中,關於讀取文件編碼解碼的問題
阿新 • • 發佈:2018-11-28
fault use ext ted ltib read name strong nco UnicodeDecodeError: ‘gbk‘ codec can‘t decode byte 0xb1 in position 94: illegal multibyte sequence
有時候用open()方法打開文件讀取文件的時候會出現這個問題:‘GBK’編×××無法解碼94號位置的字節0xb1:非法多字節序列。錯誤信息提示了使用“GBK”解碼。 1.分析 pycharm自動使用的是‘UTF-8’編碼,好像沒有什麽問題,為什麽會出現這個錯誤呢。結果查了下open()函數的註解,裏面又這麽一段話: encoding is the name of the encoding used to decode or encode the file. This should only be used in text mode. *The default encoding is platform dependent*, but any encoding supported by Python can be passed. See the codecs module for the list of supported encodings. The default encoding is platform dependent:默認編碼方式取決於平臺。這也就不奇怪會用‘GBK’編碼了,平臺不一樣,編碼方式不一樣,所以讀取的時候回出現錯誤。 2.解決方法 # 1.以byte讀取,並以‘utf-8’解碼 # fp = open(filename, ‘rb‘) # content = fp.read() # self.content = content.decode(‘utf-8‘) # fp.close() # 2.在打開文件時指定編碼方式 fp = open(filename, encoding=‘utf-8‘) content = fp.read() self.content = content fp.close() 如有不同見解,歡迎分享。
Python中,關於讀取文件編碼解碼的問題