ConfigParser 读取大写键并将它们设置为小写

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

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 ()工作得很好。但是在读取键和值时,它使键变成了小写。我不明白原因。谁能解释一下为什么会这样?

27459 次浏览

ConfigParser.ConfigParser() is documented to behave this way, in the Mapping Protocol Access section:

By default, all keys in sections are accessible in a case-insensitive manner. E.g. for option in parser["section"] yields only optionxform’ed option key names. This means lowercased keys by default.

That's because this module parses Windows INI files which are expected to be parsed case-insensitively.

You can disable this behaviour by replacing the ConfigParser.optionxform() function:

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

str passes through the options unchanged.