chardet 的英文字縮寫是
“charset(字符集) detection”,
意思是編碼偵測。
chardet 是 Python 的一個套件,
可以自動判斷文字檔案的編碼方式,
通常用在處理 CSV、JSON、XML 等純文字檔案時,
可以先使用 chardet 套件來判斷檔案的編碼,
再使用正確的編碼方式進行讀取,
避免因編碼不同而導致的資料解析錯誤。
import os
import chardet
import pandas as pd
folder = r"C:\Temp"
fname = "test.txt"
fpath = os.path.join(folder,fname)
#'C:\\Temp\\test.txt'
with open(fpath, 'rb') as f:
result = chardet.detect(f.read())
# "charset(字符集) detection"
“””注意要使用rb模式開檔,
不然會出現TypeError
File C:\ProgramData\Anaconda\lib\site-packages\chardet\__init__.py:36 in detect
raise TypeError(‘Expected object of type bytes or bytearray, got: ‘
TypeError: Expected object of type bytes or bytearray, got: <class ‘str’>
“””
print("charset(字符集) detection:\n",result)
df = pd.read_csv(fpath, encoding=result['encoding'])

推薦hahow線上學習python: https://igrape.net/30afN








![Python如何寫入docx文件? from docx import Document ; doc = Document() ; table = doc.add_table(rows=5, cols=3) ; table.cell(r,c).text = str(tabs[r][c]) ; doc.add_heading ; p = doc.add_paragraph ; p.add_run ; doc.add_picture ; 使用wordPad開啟會少最後一個row,可以用免費的LibreOffice Python如何寫入docx文件? from docx import Document ; doc = Document() ; table = doc.add_table(rows=5, cols=3) ; table.cell(r,c).text = str(tabs[r][c]) ; doc.add_heading ; p = doc.add_paragraph ; p.add_run ; doc.add_picture ; 使用wordPad開啟會少最後一個row,可以用免費的LibreOffice](https://i0.wp.com/savingking.com.tw/wp-content/uploads/2022/09/20220914154313_30.jpg?quality=90&zoom=2&ssl=1&resize=350%2C233)

近期留言