python configparser 大小写_ConfigParser导入ini配置文件关键字强制转小写解决办法

背景

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

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

测试

示范配置文件:

#conf.ini

[Path]

Player = D:\Program\vlc.exe

Editor = C:\Windows\system32\notepad.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()函数将字符串强制输出为小写。

因此解决方案有两个:

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

声明一个自己的解析类,继承原有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'}

问题解决!

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值