Python中,關於讀取檔案編碼解碼的問題
阿新 • • 發佈:2018-11-28
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() 如有不同見解,歡迎分享。