解决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'))
相关推荐
千里码aicood1 分钟前
面向智能助理的多轮医疗对话生成系统开发
python
MC皮蛋侠客4 分钟前
OPC UA 系列(一):标准全景与 Python 最小闭环——让第一条设备数据流动起来
开发语言·python·opcua
用户3721574261356 分钟前
使用 Python 提取 Word 文档中的表格数据
python
有味道的男人8 分钟前
得物详情 API|支持实时价格、成色、鉴别服务数据
windows·python·api
小溪学编程12 分钟前
Java BufferedReader 详解:从基础用法到性能优化
java·python·性能优化
2601_9623004727 分钟前
基于Python与Tkinter的ADB Monkey自动化测试脚本开发
python·adb·tkinter·android测试·gui自动化
SamChan9037 分钟前
PDF翻译后的格式完整性校验:用Python自动比对译文与原文档的表格与段落结构
开发语言·python·ai·pdf·机器翻译
2601_9620779838 分钟前
Python是一门什么样的语言?
python·编程语言·解释器·编译型·解释型
用户0190275816140 分钟前
不用 SDK 也能取 A 股数据:AlphaFeed REST API 用 cURL/HTTP 直连教程
python
君顾11 小时前
外卖CPS系统开发实战指南:从架构设计到部署全流程解析
java·开发语言·外卖