configparser is a library used to store and retrieve configuration values in Python. (Python Document)

As your program grows, you’ll definitely want to use configparser. Sometimes, I see people using a database instead of a configuration file. While using a database can improve scalability, it often feels like overkill and misses the original purpose of configuration management.

Configuration files are essential for running programs, as separating program logic from configuration values enhances reusability. This separation allows configuration values to define the environment for actions or maintain consistency when a program restarts.

The configparser module in Python helps users manage such configuration files effectively. As a standard library, configparser enables reading, writing, and modifying configuration files, primarily in the .ini format.

Configparser Code

import os
import configparser

base_dir = os.path.dirname(os.path.abspath(__file__))
config = configparser.ConfigParser(interpolation=None,
                allow_no_value=True, delimiters=('='), strict=False)

config_file = os.path.join(base_dir, 'conf', 'configure.ini')

if not os.path.exists(os.path.join(base_dir, 'conf')):
    os.mkdir(os.path.join(base_dir, 'conf'))
if not os.path.isfile(config_file):
    with open(config_file, 'w', encoding='UTF-8') as fd:
        fd.write('[lv1]\nlv2 = Value\n')

config.read(config_file, encoding='UTF-8')

print(config.sections(), '''\t: print(config.sections()''')
for item in config['lv1']:
    print(item, '''\t: print(item)''')

print(config['lv1']['lv2'], '''\t: print(config['lv1']['lv2']''')

config.set('lv1', 'lv3', 'Value')
with open(config_file, 'w', encoding='UTF-8') as configfile:
   config.write(configfile)

with open(config_file, 'r', encoding='UTF-8') as fd:
    line = fd.read()
    print(line)

configure.ini

[lv1]
lv2 = Value

All configuration values in configparser follow a 1:1 structure, pairing one key with one value. To organize these values into broader categories, sections are used. This allows items with the same name to exist in different sections without conflict.

Output

['lv1'] 	: print(config.sections()
lv2 	: print(item)
Value 	: print(config['lv1']['lv2']
[lv1]
lv2 = Value
lv3 = Value

Configparser

Key Features

  • Support for the .ini file format: Manage configuration files using a structured format with sections, keys, and values.
  • Read and write settings: Read, modify, or save configuration data to existing or new files.
  • Flexibility: Define default values and create new configuration files if they don’t already exist. and more.

Use for

  • Manage application settings
  • Save custom values
  • Separating development and deployment environments

Pros

  • Supports a simple, easy-to-read configuration file format
  • Built-in Python library, no additional installation required

Disadvantages

  • Difficult to represent complex structures (nested data) (JSON or YAML are better suited).

I’ve noticed that cloud-based programs are increasingly adopting JSON or YAML for configuration, but configparser is still a solid choice for simpler programs due to its ease of use and compatibility with the .ini format.

By Mark

-_-

Leave a Reply

Your email address will not be published. Required fields are marked *