当前位置: 首页 > news >正文

解决python配置文件类configparser.ConfigParser,插入、读取数据,自动转为小写的问题

配置类

[Section1]
Key_AAA = Value

[Section2]
AnotherKey = Value

默认情况下,ConfigParser会将ini配置文件中的KEY,转为小写。

在这里插入图片描述

重载后配置类:

  • 继承类从configparser.ConfigParser改为configparser.RawConfigParser
  • 重载方法optionxform,默认它会将数据转为小写。直接返回不转为小写。
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

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

    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'))

在这里插入图片描述

相关文章:

  • AGI成立的条件
  • 算法及数据结构系列 - 回溯算法
  • 嵌入式芯片与系统设计竞赛,值得参加吗?如何选题?需要学什么?怎么准备?
  • QT开发(4)--各种方式实现HelloWorld
  • centos 7 搭建FTP user-list用户列表
  • LeetCode算法题(Go语言实现)_07
  • ensp 公司组网拓扑图
  • 如何给商品一键换色?图生生AI,告别繁琐修图
  • html5炫酷3D立体文字效果实现详解
  • 基于PySide6的CATIA自动化工具开发实战——空几何体批量清理系统
  • GITLAB部署安装教程
  • Kubernetes Init 容器:实现 Nginx 和 PHP 对 MySQL 的依赖检查
  • 9-类、结构体、指针、引用
  • 挖矿病毒应急响应处置手册
  • 嵌入式Linux——Framebuffer应用编程
  • Milvus学习整理
  • 我在windows上创建一个空文件,这个文件在哪里存着?这个文件要不要占据磁盘空间大小?
  • JVM常见面试总结
  • PostgreSQL_数据下载并保存(psycopg2)
  • w265基于Spring Boot库存管理系统
  • 海航回应“男团粉丝为追星堵住机舱通道”:已紧急阻止
  • 江苏省委社会工作部部长等多人拟在省志愿服务联合会任职
  • 重温经典|开播20周年,仙剑的那些幕后你知道吗?
  • 上海第四批土拍成交额97亿元:杨浦宅地成交楼板单价半年涨近7000元
  • 习近平向中国人民解放军仪仗队致意
  • 第一集|《刑警的日子》很生活,《执法者们》有班味