一、檔案處理
錯誤型別:
UnicodeDecodeError: 'gbk' codec can't decode byte 0x8c in position 14: illegal multibyte sequence
1、 t 模式下的 讀操作
新建txt檔案 313.txt ——
hello world
hello day
hello me@2020
>>> f=open(r'D:\0tempt\313.txt',mode='rt') >>> print(f) <_io.TextIOWrapper name='D:\\0tempt\\313.txt' mode='rt' encoding='cp936'> >>> res=f.read() >>> print(res) hello world hello day hello mili @2020 >>>
新建txt檔案 3133.txt——
你好,世界
你好,每一天
你好,米粒
>>> f=open(r'D:\0tempt\3133.txt',mode='rt') >>> print(f) <_io.TextIOWrapper name='D:\\0tempt\\3133.txt' mode='rt' encoding='cp936'> >>> res=f.read() Traceback (most recent call last): File "<pyshell#46>", line 1, in <module> res=f.read() UnicodeDecodeError: 'gbk' codec can't decode byte 0x8c in position 14: illegal multibyte sequence >>>
UnicodeDecodeError: 'gbk' codec can't decode byte 0x8c in position 14: illegal multibyte sequence
解決方法: 指定解碼編碼格式——encoding='UTF-8'
>>> f=open(r'D:\0tempt\3133.txt',mode='rt',encoding='UTF-8') >>> print(f) <_io.TextIOWrapper name='D:\\0tempt\\3133.txt' mode='rt' encoding='UTF-8'> >>> res=f.read() >>> print(res) 你好,世界 你好,每一天 你好,米粒 >>>
=====
之前英文和數字的文本內容,讀取時沒有指定解碼編碼,沒有出錯,是因為英文和數字是不會出現亂碼現象的,使用任何編碼型別解釋器都能識別英文和數字,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/177778.html
標籤:Python
