INIParse

0.5.1 · active · verified Thu Apr 16

iniparse is an INI parser for Python designed for API compatibility with the standard library's ConfigParser. It offers enhanced functionality, including preserving the structure of INI files (order of sections & options, indentation, comments, and blank lines) when data is updated, and more convenient dotted notation access to values. The current version is 0.5.1, with infrequent releases primarily focused on Python compatibility updates.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to read an INI file, access and modify values using both dotted notation and dictionary-like syntax, add new options, and write the updated configuration back to a new file, ensuring original structure and comments are preserved. It uses `ConfigParser` from `iniparse`.

import os
from iniparse import ConfigParser

# Create a dummy INI file
ini_content = """
[mysection]
key = value
another_key = another value

[database]
host = localhost
port = 5432
user = dbuser
"""

config_file_path = 'config.ini'
with open(config_file_path, 'w') as f:
    f.write(ini_content)

# Initialize and read the INI file
cfg = ConfigParser()
cfg.read(config_file_path)

# Access values using dotted notation or dictionary-like syntax
print(f"Value for mysection.key: {cfg.mysection.key}")
print(f"Value for database.port: {cfg['database']['port']}")

# Modify a value
cfg.mysection.key = 'new_value'
print(f"Modified value for mysection.key: {cfg.mysection.key}")

# Add a new option
cfg.database.password = os.environ.get('DB_PASSWORD', 'default_password')
print(f"Added database.password: {cfg.database.password}")

# Write changes to a new INI file, preserving structure
new_config_file_path = 'new_config.ini'
with open(new_config_file_path, 'w') as f:
    cfg.write(f)

print(f"Configuration written to {new_config_file_path}")

# Clean up dummy files
os.remove(config_file_path)
os.remove(new_config_file_path)

view raw JSON →