Python configparser Tutorials

Python configparser Tutorials
Photo by Maxwell Nelson / Unsplash

1 Overview

configparser is a Python standard library module that provides an easy way to work with configuration files in the INI file format. It's commonly used to store and retrieve configuration settings for applications. Here's a tutorial on using configparser to manage configuration files:

2 Application

2.1 Importing configparser

Start by importing the configparser module:

import configparser

2.2 Creating and Writing to a Configuration File

You can create and write to a configuration file using configparser:

config = configparser.ConfigParser()

# Add sections and keys
config['Server'] = {'Port': '8080', 'Host': 'localhost'}
config['Database'] = {'Username': 'admin', 'Password': 'secret'}

# Write the configuration to a file
with open('config.ini', 'w') as configfile:
    config.write(configfile)

2.3 Reading from a Configuration File

You can read values from a configuration file using configparser:

config = configparser.ConfigParser()

# Read the configuration from a file
config.read('config.ini')

# Access values using sections and keys
port = config['Server']['Port']
host = config['Server']['Host']
username = config['Database']['Username']
password = config['Database']['Password']

print(f"Server Port: {port}")
print(f"Server Host: {host}")
print(f"Database Username: {username}")
print(f"Database Password: {password}")

2.4 Modifying Values

You can modify existing values in the configuration file:

config['Server']['Port'] = '9090'

# Write the modified configuration back to the file
with open('config.ini', 'w') as configfile:
    config.write(configfile)

2.5 Removing Sections or Keys

You can remove sections or keys from the configuration:

# Remove a key
del config['Server']['Port']

# Write the updated configuration back to the file
with open('config.ini', 'w') as configfile:
    config.write(configfile)

2.6 Handling Comments

You can add comments to your configuration file:

config = configparser.ConfigParser()

# Add a section with a comment
config['Logging'] = {'Level': 'info'}
config['Logging'].comment = "Logging settings"

# Write the configuration to a file
with open('config.ini', 'w') as configfile:
    config.write(configfile)

3 Remarks

Remember that the INI file format uses sections denoted by [section] headers and key-value pairs. You can have multiple sections with their own sets of keys. configparser also supports other features like interpolation and case sensitivity. This tutorial covers the basics, but there are more advanced features you can explore in the official Python documentation: configparser — Configuration file parser.