解决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'))
相关推荐
05候补工程师5 分钟前
【408 从零到一】线性表逻辑特征、存储结构对比与 C/C++ 动态内存分配避坑指南
c语言·开发语言·数据结构·c++·考研
yongui4783413 分钟前
MATLAB 使用遗传算法求解微电网优化配置数学模型
开发语言·matlab
郝学胜-神的一滴16 分钟前
Python 抽象基类深度解析:从简易模拟到 abc 模块的优雅实践
开发语言·python·pycharm
Python伍六七28 分钟前
给予Python开发的【16款高效办公自动化工具合集】,告别低效加班!
开发语言·python·自动化
懷淰メ30 分钟前
【AI加持】基于PyQt+YOLO+DeepSeek的舌苔情况检测系统(详细介绍)
python·yolo·目标检测·计算机视觉·pyqt·舌苔
云渊未归0630 分钟前
Python获取GitCode项目信息
python·数据分析·开源·网络爬虫·gitcode
rit843249937 分钟前
基于博弈论的小区分簇算法MATLAB实现
开发语言·算法·matlab
怕什么真理无穷43 分钟前
C++面试5_ TCP 粘包2(工业级)
开发语言·c++·tcp/ip
qingyulee1 小时前
python redis
开发语言·redis·python