解决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'))
相关推荐
lihao lihao几秒前
C++ set和map
开发语言·c++·算法
小陈phd3 分钟前
langGraph从入门到精通(三)——基于LangGraph的智能问答系统开发:Python单代理架构实战
开发语言·python·架构
轻竹办公PPT3 分钟前
AI 自动生成 PPT 实用吗?深度体验后的客观评价
人工智能·python·powerpoint
电子_咸鱼10 分钟前
Linux IPC 实战:管道与共享内存的使用场景 + 底层原理全剖析
linux·运维·服务器·开发语言·网络·vscode·qt
smile_5me11 分钟前
RK3588 csm400b调试记录
c语言·开发语言
Java后端的Ai之路14 分钟前
【Python教程02】-列表和元组
服务器·数据库·python·列表·元组
好好学仿真15 分钟前
探索超表面智能设计:当FDTD仿真遇上Python优化
python·联合仿真·机器学习算法·光学·fdtd·超表面逆向设计·超表面器件设计
C_心欲无痕15 分钟前
JavaScript 常见算法与手写函数实现
开发语言·javascript·算法
沈浩(种子思维作者)16 分钟前
量子AI真的可以在经典物理硬件中实现吗?
人工智能·python·量子计算
客卿12317 分钟前
C语言实现数组串联--力扣冒险
c语言·开发语言·leetcode