解决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'))
相关推荐
RanMatrix3 分钟前
python-logging模块
python
2501_941111934 分钟前
基于C++的区块链实现
开发语言·c++·算法
e***749510 分钟前
Redis——使用 python 操作 redis 之从 hmse 迁移到 hset
数据库·redis·python
Ace_317508877617 分钟前
京东商品详情接口终极突破:从多接口联动解析到数据全息重构
python·重构
czxyvX19 分钟前
010-C++之List
开发语言·c++·list
小艳加油26 分钟前
生态学研究突破:利用R语言多元算法实现物种气候生态位动态分析与分布预测,涵盖数据清洗、模型评价到论文写作全流程
开发语言·算法·r语言
汗流浃背了吧,老弟!26 分钟前
Langchian检索YouTube视频字幕
python·音视频
程序猿_极客30 分钟前
【2025 最新】 Maven 下载安装与配置教程(超详细带图文Windows 版):从入门到实战
java·开发语言·windows·maven·maven安装
励志前端小黑哥37 分钟前
uv包管理器--python也有自己的pnpm了
开发语言·python·uv
2501_9411120742 分钟前
深入理解Python的if __name__ == ‘__main__‘
jvm·数据库·python