ConfigParser导入ini配置文件关键字强制转小写解决办法

背景

在code中写入参数和路径等配置会导致编译后无法更改,使用配置文件可提高代码维护性。

Python自带的configparser支持通用的ini配置文件,可以获取不同分组下的键值对。

测试

示范配置文件:

#conf.ini

[Path]
Player = D:Programvlc.exe
Editor = C:Windowssystem32
otepad.exe

随后通过Python调用并生成配置字典:

from configparser import ConfigParser

conf = ConfigParser()
conf.read("./conf.ini")
path = dict(conf.items("Path"))
print(path)

# Output:
# {'player': 'D:\Program\vlc.exe', 'editor': 'C:\Windows\system32\notepad.exe'}

关键字都变成了小写,无法用于case sensitive场景,如何保留原始关键字?

优化

通过摸排,发现是ConfigParser自带的optionxfrom()方法中含有lower()函数将字符串强制输出为小写。

因此解决方案有两个:

  1. 修改自带的optionxfrom()方法,删掉lower()函数,更换环境失效。不推荐!

  2. 声明一个自己的解析类,继承原有ConfigParser并重写optionxfrom()方法,推荐!

from configparser import ConfigParser

class MyParser(ConfigParser):
    "Inherit from built-in class: ConfigParser"
    def optionxform(self,optionstr):
        "Rewrite without lower()"
        return optionstr

conf = MyParser()
conf.read("./conf.ini")
path = dict(conf.items("Path"))
print(path)

# Output:
# {'Player': 'D:\Program\vlc.exe', 'Editor': 'C:\Windows\system32\notepad.exe'}

问题解决!

原文地址:https://www.cnblogs.com/azureology/p/13177773.html