Configuration file parser in Python (configparser)

PythonProgrammingServer Side Programming

The configparser module from Python's standard library defines functionality for reading and writing configuration files as used by Microsoft Windows OS. Such files usually have .INI extension.

The INI file consists of sections, each led by a [section] header. Between square brackets, we can put the section’s name. Section is followed by key/value entries separated by = or : character. It may include comments, prefixed by # or ; symbol. A sample INI file is shown below −

[Settings]
# Set detailed log for additional debugging info
DetailedLog=1
RunStatus=1
StatusPort=6090
StatusRefresh=10
Archive=1
# Sets the location of the MV_FTP log file
LogFile=/opt/ecs/mvuser/MV_IPTel/log/MV_IPTel.log
Version=0.9 Build 4
ServerName=Unknown

[FTP]
# set the FTP server active
RunFTP=1
# defines the FTP control port
FTPPort=21
# Sets the location of the FTP data directory
FTPDir=/opt/ecs/mvuser/MV_IPTel/data/FTPdata
# set the admin Name
UserName=admin
# set the Password
Password=admin

The configparser module has ConfigParser class. It is responsible for parsing a list of configuration files, and managing the parsed database.

Object of ConfigParser is created by following statement −

parser = configparser.ConfigParser()

Following methods are defined in this class −

sections()Return all the configuration section names.
has_section()Return whether the given section exists.
has_option()Return whether the given option exists in the given section.
options()Return list of configuration options for the named section.
read()Read and parse the named configuration file.
read_file()Read and parse one configuration file, given as a file object.
read_string()Read configuration from a given string.
read_dict()Read configuration from a dictionary. Keys are section names, values are dictionaries with keys and values that should be present in the section.
get()Return a string value for the named option.
getint()Like get(), but convert value to an integer.
getfloat()Like get(), but convert value to a float.
getboolean()Like get(), but convert value to a boolean. Returns False or True.
items()return a list of tuples with (name, value) for each option in the section.
remove_section()Remove the given file section and all its options.
remove_option()Remove the given option from the given section.
set()Set the given option.
write()Write the configuration state in .ini format.

Following script reads and parses the 'sampleconfig.ini' file

import configparser
parser = configparser.ConfigParser()
parser.read('sampleconfig.ini')
for sect in parser.sections():
   print('Section:', sect)
   for k,v in parser.items(sect):
      print(' {} = {}'.format(k,v))
   print()

Output

Section: Settings
detailedlog = 1
runstatus = 1
statusport = 6090
statusrefresh = 10
archive = 1
logfile = /opt/ecs/mvuser/MV_IPTel/log/MV_IPTel.log
version = 0.9 Build 4
servername = Unknown

Section: FTP
runftp = 1
ftpport = 21
ftpdir = /opt/ecs/mvuser/MV_IPTel/data/FTPdata
username = admin
password = admin

The write() method is used to create a configuration file. Following script configures the parser object and writes it to a file object representing 'test.ini'

import configparser
parser = configparser.ConfigParser()
parser.add_section('Manager')
parser.set('Manager', 'Name', 'Ashok Kulkarni')
parser.set('Manager', 'email', 'ashok@gmail.com')
parser.set('Manager', 'password', 'secret')
fp=open('test.ini','w')
parser.write(fp)
fp.close()
raja
Published on 12-Mar-2019 12:44:19
Advertisements