ConfigParser读取大写字母并使其小写


73

我发现了一个有趣的发现。我写了一个配置文件读取程序,

import ConfigParser
class  ConfReader(object):
    ConfMap = dict()

    def __init__(self):
        self.config = ConfigParser.ConfigParser()
        self.config.read('./Config.ini')
        self.__loadConfigMap()

    def __loadConfigMap(self):
        for sec in self.config.sections():
            for key,value in self.config.items(sec):
                print 'key = ', key, 'Value = ', value
                keyDict = str(sec) + '_' + str(key)
                print 'keyDict = ' + keyDict  
                self.ConfMap[keyDict] = value

    def getValue(self, key):
        value = ''
        try:
            print ' Key = ', key
            value = self.ConfMap[key] 
        except KeyError as KE:
            print 'Key', KE , ' didn\'t found in configuration.'
    return value

class MyConfReader(object):
    objConfReader = ConfReader()

def main():
     print MyConfReader().objConfReader.getValue('DB2.poolsize')
     print MyConfReader().objConfReader.getValue('DB_NAME')

if __name__=='__main__':
    main()

我的Config.ini文件看起来像

[DB]
HOST_NAME=localhost
NAME=temp
USER_NAME=postgres
PASSWORD=mandy

__loadConfigMap()可以正常工作。但是,在读取键和值时,会使键变成小写。我不明白原因。有人可以解释为什么吗?


Answers:


125

ConfigParser.ConfigParser()是的子类ConfigParser.RawConfigParser(),据记录是这种行为:

所有选项名称均通过该optionxform()方法传递。其默认实现将选项名称转换为小写。

这是因为此模块将解析Windows INI文件,这些文件应区分大小写。

您可以通过替换RawConfigParser.optionxform()功能来禁用此行为:

self.config = ConfigParser.ConfigParser()
self.config.optionxform = str

str 通过不变的选项。


@Martijin,这意味着我需要替换ConfigParser.RawConfigParser()的代码。很好,谢谢您的解释。为我工作。
Mandy 2013年

7
感谢您解释为什么要将 ConfigParser键转换为小写。
abaumg '16

使用此选项,我看到保留了键的大写。在我的ini文件中,键和值之间没有空格。但是,配置解析器在等于之前和之后添加一个空格。例如:如果我的ini文件中有KEY = value,它将更改为KEY = value。有什么选择可以避免这些多余的空间?
sridhar249

我发现了空间问题的解决方案在这里:stackoverflow.com/questions/14021135/...
sridhar249
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.