Python通过configparser模块解析ini文件的详细步骤

作者:袖梨 2026-05-20

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

Python使用configparser模块解析ini文件的方法步骤

1. INI文件格式简介

INI配置文件采用分节结构,每个节包含若干键值对,基本语法示例如下:

[Section1]
key1 = value1
key2 = value2

[Section2]
key3 = value3
  1. 节(Section):通过[SectionName]语法实现配置项分组
  2. 键值对(Key-Value):采用key = value的基本格式
  3. 注释:支持以#;开头的注释行

2. 使用configparser模块

安装

该模块已集成在Python标准库中,无需单独安装。

基本操作流程

模块导入

import configparser

初始化解析器

config = configparser.ConfigParser()

加载配置文件

config.read('config.ini')  # 返回成功加载的文件列表

读取配置参数

value = config.get('Section1', 'key1')  # 获取字符串类型值

3. 常用方法

读取操作

获取全部节名

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)

4. 处理默认值

支持通过defaults参数预设默认节,或在读取时指定备用值:

# 优先读取DEFAULT节的配置
value = config.get('Section1', 'key1', fallback="default_value")

5. 高级配置

解析器初始化时可自定义多项参数:

config = configparser.ConfigParser(
    allow_no_value=True,   # 允许空值键
    delimiters=('=', ':'), # 自定义分隔符
    comment_prefixes=('#', ';'),  # 注释标识符
    strict=False  # 是否严格校验重复项
)

6. 示例代码

配置读取与输出

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)

7. 注意事项

  1. 大小写处理:默认转换键名为小写,可通过config = configparser.ConfigParser(converters={})关闭此功能
  2. 注释保留:原生不支持注释保留,需借助configobj等第三方库
  3. 编码问题:建议使用open函数显式指定文件编码

掌握这些方法后,即可高效处理INI配置文件。对于更复杂的需求,可考虑configobjtoml等扩展库。

本文完整介绍了Python解析INI文件的解决方案,帮助开发者快速实现配置管理功能。

相关文章

精彩推荐