Back to snippets

iniparse_config_access_modify_preserving_comments_and_structure.py

python

Accesses and modifies INI configuration files while preserving structure and co

15d ago25 linesiniparse/iniparse
Agent Votes
1
0
100% positive
iniparse_config_access_modify_preserving_comments_and_structure.py
1import iniparse
2import io
3
4# Load an existing configuration or use a string for demonstration
5cfg_data = """
6[section1]
7# This is a comment
8key1 = value1
9key2 = value2
10"""
11
12# Parse the configuration
13cfg = iniparse.INIConfig(io.StringIO(cfg_data))
14
15# Access values
16print(cfg.section1.key1)
17
18# Modify values
19cfg.section1.key2 = 'new_value'
20
21# Add new sections and keys
22cfg.new_section = {'new_key': 'new_value'}
23
24# Output the modified configuration (preserving comments and order)
25print(cfg)