Loading

Python标准组件ConfigParser配置文件解析器,保存配置时支持大写字母的方法

虽然自己已经改用xml作为配置文件首选格式了,但是有时候还是需要解析ini、cfg文件(为了兼容早期版本或者其他作者的软件)。

基本上Python自带的ConfigParser足够应对了,但是美中不足的是,configparser.RawConfigParser.write()保存文件时,会把所有key存为小写。

组件这样设计应该是为了避免key的大小写混用导致识别困难,但是如果是有特别需要自定义大小写的话,可以找到Python安装目录下的Lib\configparser.py文件的class RawConfigParser()的optionxform方法:

class RawConfigParser(MutableMapping):
    ...
    ...
    def optionxform(self, optionstr):
        return optionstr.lower()
    ...

将这里的小写函数lower()去掉:

    def optionxform(self, optionstr):
        return optionstr

这样,再保存配置文件时,key就不会自动变小写了。

posted @ 2019-06-26 15:01  gamesun  阅读(637)  评论(0编辑  收藏  举报