解決configparser讀取config.ini編碼問題

admin Python評論118字?jǐn)?shù) 554閱讀模式

在 Python 中使用 configparser 讀取 config.ini 時,常見的編碼問題主要是由于文件編碼不統(tǒng)一(如 UTF-8、GBK、ANSI 等)導(dǎo)致的 UnicodeDecodeError。以下是 4 種解決方案,涵蓋自動檢測編碼、手動嘗試常見編碼、強(qiáng)制轉(zhuǎn)換編碼等方法,并提供完整代碼示例。

使用 chardet 自動檢測編碼(推薦)

適用場景
? 適用于不確定文件編碼的情況(如用戶提供的配置文件)。
? 自動檢測編碼,兼容性最好。
代碼示例文章源自網(wǎng)吧系統(tǒng)維護(hù)-http://www.s143.cn/12848.html

import configparser
import chardet

def read_config_with_chardet(file_path):
    # 1. 檢測文件編碼
    with open(file_path, 'rb') as f:
        raw_data = f.read()
        encoding = chardet.detect(raw_data)['encoding']
    
    # 2. 用檢測到的編碼讀取文件
    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.s143.cn/12848.html文章源自網(wǎng)吧系統(tǒng)維護(hù)-http://www.s143.cn/12848.html
版權(quán)聲明:文章圖片資源來源于網(wǎng)絡(luò),如有侵權(quán),請留言刪除!!!
廣告也精彩
admin
  • 本文由 發(fā)表于 2025年9月8日 14:30:42
  • 轉(zhuǎn)載請務(wù)必保留本文鏈接:http://www.s143.cn/12848.html
匿名

發(fā)表評論

匿名網(wǎng)友 填寫信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: