解决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'))
相关推荐
喵手几秒前
Python爬虫零基础入门【第二章:网页基础·第2节】你要抓的到底是什么:HTML、CSS 选择器、XPath 入门?
爬虫·python·python爬虫实战·python爬虫工程化实战·python爬虫零基础入门·网页基础·网页结构解析
lsx2024061 分钟前
jEasyUI 条件设置行背景颜色
开发语言
飞天小蜈蚣2 分钟前
python-django_ORM的十三个查询API接口
开发语言·python·django
飞雪20075 分钟前
局域网服务发现技术, DNS-SD和mDNS具体有什么区别, 什么不同?
开发语言·局域网·mdns·airplay·dns-sd·airprint
人工智能AI技术9 分钟前
【Agent从入门到实践】18 脚本化编程:批量执行、自动化逻辑
人工智能·python
开开心心就好10 分钟前
打印机驱动搜索下载工具,自动识别手动搜
java·linux·开发语言·网络·stm32·物联网·电脑
摘星编程11 分钟前
React Native + OpenHarmony:MapView自定义标注样式
python
向量引擎14 分钟前
[硬核架构] 2026 企业级 AI 网关落地指南:从“连接超时”到“秒级响应”的架构演进(附 Python/Java 源码)
人工智能·python·gpt·ai作画·架构·aigc·api调用
0思必得016 分钟前
[Web自动化] Selenium模拟用户的常见操作
前端·python·selenium·自动化
凡客丶20 分钟前
Windows版Miniconda打包环境迁移到内网离线环境【详解】
windows·python