问题描述
我发现了一个有趣的观察结果.我写了一个配置文件读取程序,
I found one interesting observation.I had written one config file read program as,
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 文件看起来像,
And my Config.ini file looks like,
[DB]
HOST_NAME=localhost
NAME=temp
USER_NAME=postgres
PASSWORD=mandy
__loadConfigMap() 工作得很好.但是在读取键和值时,它使键小写.我不明白原因.谁能解释一下为什么会这样?
The __loadConfigMap() works just fine. But while reading the key and values, it is making the keys lower case. I didn't understand the reason. Can any one please explain why it is so?
推荐答案
ConfigParser.ConfigParser()
是 ConfigParser.RawConfigParser()
,它被记录为以这种方式运行:
ConfigParser.ConfigParser()
is a subclass of ConfigParser.RawConfigParser()
, which is documented to behave this way:
所有选项名称都通过 optionxform()
方法传递.它的默认实现将选项名称转换为小写.
这是因为该模块解析 Windows INI 文件,这些文件预计不区分大小写.
That's because this module parses Windows INI files which are expected to be parsed case-insensitively.
您可以通过替换 RawConfigParser 来禁用此行为.optionxform()
函数:
You can disable this behaviour by replacing the RawConfigParser.optionxform()
function:
self.config = ConfigParser.ConfigParser()
self.config.optionxform = str
str
传递选项不变.
这篇关于ConfigParser 读取大写键并使它们小写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!