很多情況下我們是這樣讀取文本文件的:
with open(r'F:\.Python Project\spidertest1\test\pdd涼席.txt', 'r') as f:
text = f.read()
但是如果該文本文件是gbk格式的,那么將會報以下錯誤:
Traceback (most recent call last):
File "F:/.Python Project/spidertest1/test/MyTest4.py", line 14, in <module>
text = f.read()
UnicodeDecodeError: 'gbk' codec can't decode byte 0xa4 in position 1129: illegal multibyte sequence
查了下資料說是添加encoding='utf-8',這個參數:
with open(r'F:\.Python Project\spidertest1\test\pdd涼席.txt', 'r', encoding='utf-8') as f:
text = f.read()
但是這種方式治標不治本,原因就在於你根本不知道用戶打開的是utf-8的文本文件還是gbk的或者是Unicode的
所以只能采取以下這種辦法:
open('x:xxxx','rb'):
第二個參數為:'rb' 以二進制格式打開一個文件用於只讀。這就避免了指定了encoding與文件實際編碼不匹配而報錯的問題
import chardet
def check_code(text):
adchar = chardet.detect(text)
# 由於windows系統的編碼有可能是Windows-1254,打印出來后還是亂碼,所以不直接用adchar['encoding']編碼
#if adchar['encoding'] is not None:
# true_text = text.decode(adchar['encoding'], "ignore")
if adchar['encoding'] == 'gbk' or adchar['encoding'] == 'GBK' or adchar['encoding'] == 'GB2312':
true_text = text.decode('GB2312', "ignore")
else:
true_text = text.decode('utf-8', "ignore")
return true_text
def read_file_text(file_url):
# 第二個參數為:'rb' 以二進制格式打開一個文件用於只讀。這就避免了指定了encoding與文件實際編碼不匹配而報錯的問題
with open(file_url, 'rb') as f:
file_text = f.read()
file_text = check_code(file_text)
return file_text