Devnet
Python
Python Configparser Module

ConfigParser Python Module

The ConfigParser Python module facilitates management of configuration files and comes bundled with the standard Python library, eliminating the need for external installations from repositories like PyPi.org.

Configuration files typically store data vital for program execution, such as parameters, options, credentials, or keys. These files can be generated using the module or manually authored, adhering to a structure reminiscent of INI files.

[DEFAULT]
username = admin
password = admin123
port = 22
 
[server_a]
ip_address = 192.168.1.10
 
[server_b]
ip_address = 192.168.1.20
 
[switch]
password = switch123
ip_address = 192.168.1.100
port = 23

Configuration files are divided into sections denoted within square brackets. Each section consists of key-value pairs, separated by '=' or ':'. While section names are case-sensitive, keys are not. When interacting with the configparser module, keys are referred to as options and the key-value pairs as items.

The provided example showcases a configuration file with three sections. Leading and trailing whitespace is ignored when parsing files using the configparser module.

Values from the DEFAULT section are accessible across all other sections. For instance, the username is defined once and applies universally. However, unique values like password and port for accessing the switch are specific to the switch section.

Parsing Configuration Data

import configparser
 
file_config = configparser.ConfigParser()
file_config.read('access_info.ini')
 
string_config = configparser.ConfigParser()
config_example = """
[DEFAULT]
username = admin
password = admin123
 
[server]
ip_address = 192.168.1.10
"""
string_config.read_string(config_example)
 
dict_config = configparser.ConfigParser()
dict_config.read_dict({
    "DEFAULT": {"username": "admin", "password": "admin123"},
    "server": {"ip_address": "192.168.1.10"}
})

The example demonstrates three methods of parsing configuration data. Objects created with ConfigParser() represent different parsing contexts: from file, string, or dictionary. Each method facilitates parsing configurations in diverse formats.

Accessing Configuration Values

config = configparser.ConfigParser()
config.read('access_info.ini')
 
# Accessing values
server_a_username = config['server_a']['username']
server_a_password = config['server_a']['password']
server_a_ip_address = config['server_a']['ip_address']
server_a_port = config['server_a']['port']
 
server_b_username = config['server_b']['username']
server_b_password = config['server_b']['password']
server_b_ip_address = config['server_b']['ip_address']
server_b_port = config['server_b']['port']
 
switch_username = config['switch']['username']
switch_password = config['switch']['password']
switch_ip_address = config['switch']['ip_address']
switch_port = config['switch']['port']

After parsing a configuration file, accessing values is akin to querying a Python dictionary. Values can be retrieved using section and option names. Utilizing this method, specific configuration data can be extracted as needed.

Manipulating Configuration Items

switch_config = config['switch']
 
# Accessing items
for item in switch_config.items():
    print(item)
 
# Checking for option presence
'Username' in switch_config
 
# Getting option value
switch_password = switch_config.get('password')
 
# Modifying values
switch_config['password'] = 'NewPassword123'
switch_config['config_file'] = '/home/configs/switch'
 
# Removing options and sections
config.remove_option('server_b', 'ip_address')
config.remove_section('server_b')
 
# Writing modified configuration to file
with open('server_access_modified.ini', 'w') as configfile:
    config.write(configfile)

Sections in a ConfigParser object enable direct access to configuration items, akin to dictionary manipulation. Operations like iterating through items, checking option presence, getting option values, modifying values, and removing options or sections are supported. Additionally, modified configurations can be written back to files seamlessly.

Conclusion

The ConfigParser module provides a robust toolkit for managing configuration files in Python. With functionalities for parsing, accessing, modifying, and writing configurations, it streamlines the handling of vital program data. Utilize its capabilities to ensure efficient configuration management within your Python projects.