在 Python 中使用 configparser 讀取 config.ini 時(shí),常見的編碼問題主要是由于文件編碼不統(tǒng)一(如 UTF-8、GBK、ANSI 等)導(dǎo)致的 UnicodeDecodeError。以下是 4 種解決方案,涵蓋自動(dòng)檢測(cè)編碼、手動(dòng)嘗試常見編碼、強(qiáng)制轉(zhuǎn)換編碼等方法,并提供完整代碼示例。
使用 chardet 自動(dòng)檢測(cè)編碼(推薦)
適用場(chǎng)景
? 適用于不確定文件編碼的情況(如用戶提供的配置文件)。
? 自動(dòng)檢測(cè)編碼,兼容性最好。
代碼示例文章源自網(wǎng)吧系統(tǒng)維護(hù)-http://www.hvig.cn/12848.html
import configparser
import chardet
def read_config_with_chardet(file_path):
# 1. 檢測(cè)文件編碼
with open(file_path, 'rb') as f:
raw_data = f.read()
encoding = chardet.detect(raw_data)['encoding']
# 2. 用檢測(cè)到的編碼讀取文件
config = configparser.ConfigParser()
config.read(file_path, encoding=encoding)
return config
# 使用示例
config = read_config_with_chardet('config.ini')
print(config.sections())
文章源自網(wǎng)吧系統(tǒng)維護(hù)-http://www.hvig.cn/12848.html文章源自網(wǎng)吧系統(tǒng)維護(hù)-http://www.hvig.cn/12848.html 版權(quán)聲明:文章圖片資源來源于網(wǎng)絡(luò),如有侵權(quán),請(qǐng)留言刪除!!!


評(píng)論