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如何串接OpenAI /Claude /Gemini API自動將大量維修紀錄JSON轉自然語言描述(並避免中斷資料遺失)response = client.chat.completions.create() ; reply = response.choices[0].message.content Python如何串接OpenAI /Claude /Gemini API自動將大量維修紀錄JSON轉自然語言描述(並避免中斷資料遺失)response = client.chat.completions.create() ; reply = response.choices[0].message.content](https://i1.wp.com/savingking.com.tw/wp-content/uploads/2025/07/20250716084059_0_c5b368.png?quality=90&zoom=2&ssl=1&resize=350%2C233)







![Python: List[ pandas.Series ] 轉DataFrame技巧:正確理解row和column的關係,同 concat( List[ pandas.Series ], axis=1 ).T Python: List[ pandas.Series ] 轉DataFrame技巧:正確理解row和column的關係,同 concat( List[ pandas.Series ], axis=1 ).T](https://i1.wp.com/savingking.com.tw/wp-content/uploads/2025/04/20250422150133_0_1cfa94.png?quality=90&zoom=2&ssl=1&resize=350%2C233)

近期留言