解决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'))
相关推荐
程序员的世界你不懂13 分钟前
Appium+python自动化(八)- 认识Appium- 下章
python·appium·自动化
_r0bin_40 分钟前
前端面试准备-7
开发语言·前端·javascript·fetch·跨域·class
zhang988000041 分钟前
JavaScript 核心原理深度解析-不停留于表面的VUE等的使用!
开发语言·javascript·vue.js
恸流失43 分钟前
DJango项目
后端·python·django
Julyyyyyyyyyyy2 小时前
【软件测试】web自动化:Pycharm+Selenium+Firefox(一)
python·selenium·pycharm·自动化
Fanxt_Ja3 小时前
【JVM】三色标记法原理
java·开发语言·jvm·算法
蓝婷儿3 小时前
6个月Python学习计划 Day 15 - 函数式编程、高阶函数、生成器/迭代器
开发语言·python·学习
love530love3 小时前
【笔记】在 MSYS2(MINGW64)中正确安装 Rust
运维·开发语言·人工智能·windows·笔记·python·rust
水银嘻嘻3 小时前
05 APP 自动化- Appium 单点触控& 多点触控
python·appium·自动化
slandarer3 小时前
MATLAB | 绘图复刻(十九)| 轻松拿捏 Nature Communications 绘图
开发语言·matlab