1 min read

Python Configparser Module

The configparser module provides a way to handle configuration files which are similar to Microsoft Windows INI files. It is part of the standard library.

Importing the Module

import configparser

The Configuration File Format

Configuration files are organized into sections, and each section contains key-value pairs.

config.ini:

[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9

[bitbucket.org]
User = hg

[topsecret.server.com]
Port = 50022
ForwardX11 = no

Creating a Config File

You can create a configuration file programmatically.

import configparser

config = configparser.ConfigParser()

config['DEFAULT'] = {'ServerAliveInterval': '45',
                     'Compression': 'yes',
                     'CompressionLevel': '9'}

config['bitbucket.org'] = {}
config['bitbucket.org']['User'] = 'hg'

config['topsecret.server.com'] = {}
topsecret = config['topsecret.server.com']
topsecret['Port'] = '50022'
topsecret['ForwardX11'] = 'no'

with open('example.ini', 'w') as configfile:
    config.write(configfile)

Reading a Config File

import configparser

config = configparser.ConfigParser()
config.read('example.ini')

# List sections
print(config.sections())
# Output: ['bitbucket.org', 'topsecret.server.com']

Accessing Values

You can access values like a dictionary. By default, values are strings. Use helper methods for types.

print(config['bitbucket.org']['User']) # 'hg'

# Get Integer
port = config['topsecret.server.com'].getint('Port')

# Get Boolean (handles 'yes', 'no', 'on', 'off', '1', '0')
forward_x11 = config['topsecret.server.com'].getboolean('ForwardX11')

programming/python/python