Monday, October 23, 2017

Parsing configuration files using ConfigParser in Python

ConfigParser is used to parse configuration file easily in python. A configuration file  can be grouped by  sections with [section] header,  and entries can be added as in name: value  order.

Eg: settings.cfg



In python;

import ConfigParser

  def loadSettings(self):
        config = ConfigParser.ConfigParser()'./config/settings.cfg')  
        if config.has_section('CustomerSettings'):
            if len(config.options('CustomerSettings')) >0:
                for key,value in config.items('CustomerSettings'):
                    print value

        if config.has_section('LogSettings') :
            if len(config.options('LogSettings')) >0:            
                filepath = config.get('LogSettings', config.options('LogSettings')[0])
                print filepath  

No comments:

Post a Comment