解决python配置文件类configparser.ConfigParser,插入、读取数据,自动转为小写的问题

配置类

复制代码
[Section1]
Key_AAA = Value

[Section2]
AnotherKey = Value

默认情况下,ConfigParser会将ini配置文件中的KEY,转为小写。

重载后配置类:

  • 继承类从configparser.ConfigParser改为configparser.RawConfigParser
  • 重载方法optionxform,默认它会将数据转为小写。直接返回不转为小写。
python 复制代码
class ConfigParser(configparser.RawConfigParser):

    def __init__(self):
        super().__init__()
        self.read(Path(BASE_PATH).joinpath('auto-api-test.ini'), encoding='utf-8')

    def optionxform(self, optionstr: str) -> str:
        """
        重载此方法,数据不转为小写
            默认情况下,这个方法会转换每次 read, get, 或 set 操作的选项名称。
            默认会将名称转换为小写形式。
            这也意味着当一个配置文件被写入时,所有键都将为小写形式。
        :param optionstr:
        :return:
        """
        return optionstr

历史配置类ConfigParser

python 复制代码
class ConfigParser(configparser.ConfigParser):

    def __init__(self):
        super().__init__()
        self.read(Path(BASE_PATH).joinpath('auto-api-test.ini'), encoding='utf-8')

普通调用RawConfigParser

官方文档:https://docs.python.org/zh-cn/3.6/library/configparser.html#configparser.ConfigParser.optionxform

python 复制代码
    def test_demo6(self):
        config = """
            [Section1]
            Key_AAA = Value
            
            [Section2]
            AnotherKey = Value
        """
        custom = configparser.RawConfigParser()
        custom.optionxform = lambda option: option
        custom.read_string(config)
        print(custom['Section1'].keys())
        # ['Key']
        print(custom['Section2'].keys())
        # ['AnotherKey']

        # 读取key
        print(custom.get('Section2', 'AnotherKey'))
相关推荐
许彰午15 分钟前
100_Python面试常见问题汇总
java·python·面试
皓悦编程记18 分钟前
【YOLO26 系列】基于YOLO26的垃圾分类检测系统【python源码+Pyqt5界面/WEB+数据集+训练代码】
python·qt·分类
滴滴滴嘟嘟嘟.27 分钟前
强化学习消融实验-batch_size / clip_range / gae_lambda / lr
python·机器学习
2601_9639329835 分钟前
怀孕四个月能做流产吗?中期妊娠终止方式与子宫修护科普指南
python
zhr_math_king37 分钟前
LangGraph-快速入门-第一个例子
python·langchain
爱吃苹果的梨叔1 小时前
2026年指挥中心分布式坐席怎么选?清虹创智让多系统、多坐席和大屏真正协同
python
没钥匙的锁12 小时前
16-Java反射机制:Spring IOC背后的核心技术
java·开发语言·spring
起予者汝也2 小时前
Python 数据结构
开发语言·数据结构·python
LadenKiller2 小时前
2026年量化工具增量,放回回测模拟实盘阶段判断
人工智能·python
石一峰6992 小时前
驱动:私有数据为什么要在三个地方各挂一遍?
数据库·python·算法