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

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

在这里插入图片描述


http://www.kler.cn/a/595454.html

相关文章:

  • LLM之向量数据库Chroma milvus FAISS
  • SOFAStack-00-sofa 技术栈概览
  • ip2region与express最佳实践
  • Linux 文件系统的日志模式与性能影响
  • RC6在线加密工具
  • PaddleSpeech-语音处理-安装【超简洁步骤】
  • 关于 Redis 缓存一致
  • 北京南文观点:AI掘金术激活算法中的“沉默用户”
  • python爬虫解析器bs4,xpath,pquery
  • 【如何打包docker大镜像】
  • 鸿蒙NEXT项目实战-百得知识库03
  • docker安装向量数据库Milvus及可视化工具 Attu
  • 复习HCIA
  • ngx_http_add_listen
  • 在R中读入h5ad文件,并转换为seurat对象
  • 闻所闻尽:穿透声音的寂静,照见生命的本真
  • 一文讲清 C++ CRTP(Curiously Recurring Template Pattern,奇异递归模板模式)
  • 基于Nvidia Jetson Nano边缘计算设备使用TensorRT部署YOLOv8模型实现目标检测推理
  • CHM(ConcurrentHashMap)中的 sizeCtl 的作用与值变化详解
  • 批量删除 PPT 空白幻灯片页面