Configuration file parser in Python (configparser)

The configparser module from Python's standard library provides 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

Creating ConfigParser Object

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 ?

import configparser
parser = configparser.ConfigParser()

ConfigParser Methods

Following methods are defined in the ConfigParser 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.

Reading Configuration Files

First, create a sample configuration file to work with ?

# Create a sample config file
config_content = """[Settings]
DetailedLog=1
RunStatus=1
StatusPort=6090
Archive=1
LogFile=/opt/ecs/mvuser/MV_IPTel/log/MV_IPTel.log

[FTP]
RunFTP=1
FTPPort=21
UserName=admin
Password=admin"""

with open('sampleconfig.ini', 'w') as f:
    f.write(config_content)

print("Configuration file created successfully!")
Configuration file created successfully!

Now let's read and parse the configuration 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()
Section: Settings
detailedlog = 1
runstatus = 1
statusport = 6090
archive = 1
logfile = /opt/ecs/mvuser/MV_IPTel/log/MV_IPTel.log

Section: FTP
runftp = 1
ftpport = 21
username = admin
password = admin

Writing Configuration Files

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

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

with open('test.ini', 'w') as fp:
    parser.write(fp)

print("Configuration file 'test.ini' created successfully!")

# Read and display the created file
with open('test.ini', 'r') as fp:
    print("\nContents of test.ini:")
    print(fp.read())
Configuration file 'test.ini' created successfully!

Contents of test.ini:
[Manager]
name = Ashok Kulkarni
email = ashok@gmail.com
password = secret

Retrieving Specific Values

You can retrieve specific values using get(), getint(), and other type-specific methods ?

import configparser

parser = configparser.ConfigParser()
parser.read('sampleconfig.ini')

# Get string value
log_file = parser.get('Settings', 'logfile')
print(f"Log file: {log_file}")

# Get integer value
status_port = parser.getint('Settings', 'statusport')
print(f"Status port: {status_port} (type: {type(status_port)})")

# Get boolean value
archive = parser.getboolean('Settings', 'archive')
print(f"Archive enabled: {archive} (type: {type(archive)})")
Log file: /opt/ecs/mvuser/MV_IPTel/log/MV_IPTel.log
Status port: 6090 (type: <class 'int'>)
Archive enabled: True (type: <class 'bool'>)

Conclusion

The configparser module provides an easy way to handle INI configuration files in Python. Use read() to load files, type-specific get methods to retrieve values, and write() to save configurations.

Updated on: 2026-03-25T05:29:11+05:30

15K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements