INI files provide a straightforward way to store application setings in a structured format. These text-based files organize configurations into sections containing key-value pairs, making them both human-readable and programmatically accessible.
Basic INI File Structure
INI files consist of:
- Sections: Enclosed in square brackets
[], these group related settings - Keys: Unique identifiers for configuration values
- Values: Data associated with each key, separated by
=or:
Example configuration:
[Database]
host = localhost
port = 5432
[Logging]
level = DEBUG
file_path = /var/log/app.log
Reading INI Files in Python
Python's configparser module handles INI file operations:
import configparser
settings = configparser.ConfigParser()
settings.read('app_config.ini')
# Accessing values
db_host = settings.get('Database', 'host')
log_level = settings.get('Logging', 'level')
print(f"Database host: {db_host}")
print(f"Log level: {log_level}")
Advanced Operasions
# Check if section exists
if 'Database' in settings:
# Get all keys in section
db_keys = settings.options('Database')
print(f"Database keys: {db_keys}")
# Update a value
settings.set('Database', 'port', '5433')
# Add new configuration
settings.add_section('Cache')
settings.set('Cache', 'ttl', '3600')
# Save changes
with open('app_config.ini', 'w') as config_file:
settings.write(config_file)
Key methods include:
sections(): List all sectionsitems(section): Get all key-value pairs in a sectionhas_section()/has_option(): Check for section/key existenceremove_section()/remove_option(): Delete confiugration elements