Python内置的configparser模块为解析INI文件提供了高效解决方案。本文将详细介绍其使用方法与实用技巧。

INI配置文件采用分节结构,每个节包含若干键值对,基本语法示例如下:
[Section1] key1 = value1 key2 = value2 [Section2] key3 = value3
[SectionName]语法实现配置项分组key = value的基本格式#或;开头的注释行该模块已集成在Python标准库中,无需单独安装。
基本操作流程
模块导入:
import configparser
初始化解析器:
config = configparser.ConfigParser()
加载配置文件:
config.read('config.ini') # 返回成功加载的文件列表
读取配置参数:
value = config.get('Section1', 'key1') # 获取字符串类型值
获取全部节名:
sections = config.sections() # 返回节名称列表
查询节内所有键:
keys = config.options('Section1') # 返回键名列表
获取键值对集合:
items = config.items('Section1') # 返回(key,value)元组列表
类型化读取:
# 自动类型转换方法
value_int = config.getint('Section1', 'key1')
value_float = config.getfloat('Section1', 'key2')
value_bool = config.getboolean('Section2', 'key3')
存在性检查:
has_section = config.has_section('Section1')
has_key = config.has_option('Section1', 'key1')
新增配置项:
config.add_section('NewSection')
config.set('NewSection', 'new_key', 'new_value')
删除配置项:
config.remove_option('Section1', 'key1')
config.remove_section('Section1')
配置文件保存:
with open('new_config.ini', 'w') as f:
config.write(f)
支持通过defaults参数预设默认节,或在读取时指定备用值:
# 优先读取DEFAULT节的配置
value = config.get('Section1', 'key1', fallback="default_value")
解析器初始化时可自定义多项参数:
config = configparser.ConfigParser(
allow_no_value=True, # 允许空值键
delimiters=('=', ':'), # 自定义分隔符
comment_prefixes=('#', ';'), # 注释标识符
strict=False # 是否严格校验重复项
)
import configparser
config = configparser.ConfigParser()
config.read('config.ini')
for section in config.sections():
print(f'[{section}]')
for key, value in config.items(section):
print(f'{key} = {value}')
config.set('Section1', 'key1', 'updated_value')
config.add_section('NewSection')
config.set('NewSection', 'new_key', '123')
with open('updated_config.ini', 'w') as f:
config.write(f)
config = configparser.ConfigParser(converters={})关闭此功能configobj等第三方库open函数显式指定文件编码掌握这些方法后,即可高效处理INI配置文件。对于更复杂的需求,可考虑configobj或toml等扩展库。
本文完整介绍了Python解析INI文件的解决方案,帮助开发者快速实现配置管理功能。