解决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'))
相关推荐
️停云️几秒前
C++异常与智能指针
开发语言·c++
m0_488913012 分钟前
Deep Research技术全解析:从Reasoning到Research with Reasoning的AI进化之路(值得收藏)
开发语言·人工智能·机器学习·大模型·ai大模型·大模型学习
烤麻辣烫6 分钟前
黑马程序员苍穹外卖(新手)DAY8
java·开发语言·学习·spring·intellij-idea
就叫飞六吧7 分钟前
Java 中编译一个 java 源文件产生多个 .class 文件原因
java·开发语言
z***89718 分钟前
Flask框架中SQLAlchemy的使用方法
后端·python·flask
IMPYLH10 分钟前
Lua 的 rawset 函数
开发语言·笔记·单元测试·lua
G果13 分钟前
ROS2 Cartographer纯定位导航遇到的问题
python·ros2·定位·cartographer·导航·launch·navigation2
python零基础入门小白14 分钟前
2025年大模型面试通关秘籍!大厂高频LLMs真题全解析,一文掌握,助你轻松斩获心仪offer!
开发语言·人工智能·语言模型·架构·langchain·大模型教程·大模型面试
chenyuhao202422 分钟前
MySQL事务
开发语言·数据库·c++·后端·mysql
g***789125 分钟前
Java语法进阶
java·开发语言·jvm