Using ConfigObj to Read, Write, and Manage INI Files in Python
This article introduces Python's ConfigObj library for parsing INI files, demonstrating how to read configuration values, write new settings, update existing entries, handle multiple files, and dynamically generate sections and options, with five practical code examples for API automation tasks.
ConfigObj is a powerful third‑party Python library that simplifies reading and writing INI configuration files, which are essential in API automation and other backend tasks.
Reading a configuration file
from configobj import ConfigObj
# 读取配置文件
config = ConfigObj('config.ini')
# 获取配置项的值
base_url = config['API']['base_url']
api_key = config['API']['api_key']
print("Base URL:", base_url)
print("API Key:", api_key)Writing a new configuration file
from configobj import ConfigObj
# 创建配置文件对象
config = ConfigObj()
# 添加配置项和值
config['API'] = {'base_url': 'https://api.example.com',
'api_key': 'your-api-key'}
# 写入配置文件
config.write(open('config.ini', 'w'))
print("配置文件写入成功!")Updating an existing configuration value
from configobj import ConfigObj
# 读取配置文件
config = ConfigObj('config.ini')
# 更新配置项的值
config['API']['api_key'] = 'new-api-key'
# 写入更新后的配置文件
config.write()
print("配置项的值已更新!")Handling multiple configuration files
from configobj import ConfigObj
# 创建配置文件对象
config = ConfigObj()
# 读取多个配置文件
config.merge(ConfigObj('config.ini'))
config.merge(ConfigObj('config_override.ini'))
# 获取配置项的值(优先使用 override 文件中的配置)
base_url = config['API']['base_url']
api_key = config['API']['api_key']
print("Base URL:", base_url)
print("API Key:", api_key)Dynamic generation of sections and options
from configobj import ConfigObj
# 创建配置文件对象
config = ConfigObj()
# 动态生成节和选项
sections = ['API', 'Database']
options = {'API': ['base_url', 'api_key'],
'Database': ['host', 'username', 'password']}
for section in sections:
config[section] = {}
for option in options[section]:
value = input(f"请输入 {option} 的值:")
config[section][option] = value
# 写入配置文件
config.write()
print("配置文件已生成!")These examples show how to flexibly read, create, update, merge, and dynamically generate INI configuration files using ConfigObj, helping developers streamline interface automation workflows.
Test Development Learning Exchange
Test Development Learning Exchange
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.