解决configparser读取config.ini编码问题

admin Python评论5字数 554阅读模式

在 Python 中使用 configparser 读取 config.ini 时,常见的编码问题主要是由于文件编码不统一(如 UTF-8、GBK、ANSI 等)导致的 UnicodeDecodeError。以下是 4 种解决方案,涵盖自动检测编码、手动尝试常见编码、强制转换编码等方法,并提供完整代码示例。

使用 chardet 自动检测编码(推荐)

适用场景
• 适用于不确定文件编码的情况(如用户提供的配置文件)。
• 自动检测编码,兼容性最好。
代码示例文章源自网吧系统维护-https://www.58pxe.com/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())
文章源自网吧系统维护-https://www.58pxe.com/12848.html文章源自网吧系统维护-https://www.58pxe.com/12848.html
版权声明:文章图片资源来源于网络,如有侵权,请留言删除!!!
广告也精彩
admin
  • 本文由 发表于 2025年9月8日 14:30:42
  • 转载请务必保留本文链接:https://www.58pxe.com/12848.html
匿名

发表评论

匿名网友 填写信息

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