ConfigParser reads capital keys and make them lower case

PythonPython 2.7

Python Problem Overview


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()

And my Config.ini file looks like,

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

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?

Python Solutions


Solution 1 - Python

ConfigParser.ConfigParser() is a subclass of ConfigParser.RawConfigParser(), which is documented to behave this way:

> All option names are passed through the optionxform() method. Its default implementation converts option names to lower case.

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 RawConfigParser.optionxform() function:

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

str passes through the options unchanged.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMandyView Question on Stackoverflow
Solution 1 - PythonMartijn PietersView Answer on Stackoverflow