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

[LogSettings]
filepath='/Users/ratha/Desktop/Twisted.log'

[CustomerSettings]
customer1='/Users/ratha/Desktop/customer1'
customer2='/Users/ratha/Desktop/customer2'


In python;

import ConfigParser

  def loadSettings(self):
        config = ConfigParser.ConfigParser()
        config.read('./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