You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python 3读取多编码INI文件并展示内容的技术实现方案

Python读取多编码INI文件的实践方案

近期我在Python字符串编码与文件编码问题上做了不少探索,现在对实际场景有了更清晰的认识。Windows系统会根据语言或语言组采用不同编码格式存储文本文件,我的需求是读取不同编码的INI文件,提取其中的键值对用于界面表单和菜单的显示。我尝试了两种实现方案:

方案一:借助magic库检测编码,使用ConfigParser读取INI文件

from configparser import ConfigParser
import magic

def detect(iniFileName):
    return magic.Magic(mime_encoding=True).from_file(iniFileName)
#---------------------------------------------------------------------------

encoding = detect('config.ini')
ini = ConfigParser()
ini.read('config.ini', encoding)
title = ini.get('USERENTRY-FORM', 'TITLE')
'''
then title is passed to the tk form
'''
UserEntryForm.setTitle(title)
if _DEBUG == True:
   print("USERENTRY-FORM title=",title)

方案二:采用chardet库检测编码,结合封装ConfigParser的AIniParser类读取(编码识别效果更优,目前测试中)

from chardet import detect

def chardetPrint(filename):
    text = open(filename, 'rb').read()
    print(filename,": ",detect(text))
#---------------------------------------------------------------------------

def chardet(filename):
    text = open(filename, 'rb').read()
    print(filename,": ",detect(text)['encoding'])   # only for test
    return detect(text)['encoding']

if __name__ == '__main__':
    from ainiparser import AIniParser
    
    def testIniRead(filename, section, key):
        with open(filename, "rb") as f:
            line = f.readline()
            print("line 1: ", line)
            
        encode = chardet(filename)
        ini = AIniParser(filename, encoding=encode)
        ini._open()
        text = ini.getString(section, key)
        print(text)
        
    
    def main():
        testIniRead("../cdata/config-cro-16.ini", "CGUIINTF", "game-turn-text")
        testIniRead("../bat/output-lva-16/idata/config-lva-16.ini", "CGUIINTF", "game-turn-text")
        testIniRead("../idata/config-lva-16.ini", "CGUIINTF", "game-turn-text")
        testIniRead("../idata/domande.ini", "D2", "B")
    #---------------------------------------------------------------------------
        
    main()

内容的提问来源于stack exchange,提问作者Massimo Manca

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 16:20:38