当前位置: 代码网 > it编程>前端脚本>Python > Python使用configparser模块管理ini格式配置文件

Python使用configparser模块管理ini格式配置文件

2026年08月25日 Python 我要评论
在 python 开发中,配置文件是管理应用程序设置的重要方式。configparser 模块提供了处理 .ini 格式配置文件的强大功能,本文将详细介绍其使用方法。configparser官方文档:

在 python 开发中,配置文件是管理应用程序设置的重要方式。configparser 模块提供了处理 .ini 格式配置文件的强大功能,本文将详细介绍其使用方法。

configparser官方文档:https://docs.python.org/3/library/configparser.html

一、configparser 简介

configparser 是 python 标准库中的模块,用于读取和写入类似 ini 格式的配置文件。这种文件结构清晰,便于管理和修改配置项。

配置文件的基本结构如下:

[simple values]
key=value
spaces in keys=allowed
spaces in values=allowed as well
spaces around the delimiter = obviously
you can also use : to delimit keys from values
[all values are strings]
values like this: 1000000
or this: 3.14159265359
are they treated as numbers? : no
integers, floats and booleans are held as: strings
can use the api to get converted values directly: true
[multiline values]
chorus: i'm a lumberjack, and i'm okay
    i sleep all night and i work all day
[no values]
key_without_value
empty string value here =
[you can use comments]
# like this
; or this
# by default only in an empty line.
# inline comments can be harmful because they prevent users
# from using the delimiting characters as parts of values.
# that being said, this can be customized.
    [sections can be indented]
        can_values_be_as_well = true
        does_that_mean_anything_special = false
        purpose = formatting for readability
        multiline_values = are
            handled just fine as
            long as they are indented
            deeper than the first line
            of a value
        # did i mention we can indent comments, too?
  • section_name:配置节的名称,使用方括号 [] 包围。
  • key:配置项的名称。
  • value:配置项的值

注释可以使用 #; 开头,必须独立成行。

[default] section会给所有section提供选项的默认值。section名的字母大小写敏感,option名的字母大小写不敏感。值可以跨行,但需要缩进。

二、读取配置文件

1. 读取配置文件内容

首先,需要导入 configparser 模块并读取配置文件:

import configparser

config = configparser.configparser()
config.read('config.ini', encoding='utf-8')

# 另一种写法:
# with open("config.ini", "r", encoding="utf-8") as f:
#    config.read_file(f)

其中,'config.ini' 是配置文件的路径,encoding='utf-8' 指定文件编码。

一次导入多个配置文件或者多次导入配置文件时,冲突选项会用新的配置文件的值。

2. 获取所有的 section

使用 sections() 方法可以获取配置文件中所有的节:

sections = config.sections()
print(sections)

3. 获取指定 section 的所有 options

使用 options(section) 方法可以获取指定节中的所有配置项名称:

options = config.options('section_name')
print(options)

4. 获取指定 section 的所有键值对

使用 items(section) 方法可以获取指定节中的所有键值对:

items = config.items('section_name')
print(items)

5. 获取指定 option 的值

config的get(section, option):默认获取字符串值

value = config.get('section_name', 'option_name')
print(value)
config.get('forge.example', 'monster',
			fallback='no such things as monsters')

如果需要获取整数、浮点数或布尔值,可以使用 getint()getfloat()getboolean() 方法。getboolean() 可以识别 ‘yes’/‘no’, ‘on’/‘off’, ‘true’/‘false’ and ‘1’/‘0’

section的get(option, fallback_value):跟字典的get()方法差不多。需要注意的是[default] section的默认值的优先级比这里的入参fallback_value要高

  • config["section_name"]
  • config["section_name"]["option_name"]

三、写入配置文件

1. 添加新的 section 和 option

可以使用 add_section() 方法添加新的节,使用 set() 方法添加配置项:

config.add_section('new_section')
config.set('new_section', 'new_option', 'value')

也可以直接把一整个字典作为一节:

import configparser
config = configparser.configparser()
config['default'] = {'serveraliveinterval': '45',
                     'compression': 'yes',
                     'compressionlevel': '9'}

2. 写入配置文件

使用 write() 方法将配置写入文件:

with open('config.ini', 'w', encoding='utf-8') as configfile:
    config.write(configfile)

四、修改和删除配置项

1. 修改配置项的值

使用 set() 方法可以修改已有配置项的值:

config.set('section_name', 'option_name', 'new_value')

2. 删除配置项或节

使用 remove_option() 方法删除配置项,使用 remove_section() 方法删除节:

config.remove_option('section_name', 'option_name')
config.remove_section('section_name')

五、检查配置项或节是否存在

使用 has_section()has_option() 方法可以检查配置文件中是否存在指定的节或配置项:

config.has_section('section_name')
config.has_option('section_name', 'option_name')

六、从字符串或字典读取配置

1. 从字符串读取配置

使用 read_string() 方法可以从字符串读取配置:

config.read_string("""
[section_name]
option_name = value
""")

2. 从字典读取配置

使用 read_dict() 方法可以从字典读取配置:

config.read_dict({
    'section_name': {
        'option_name': 'value'
    }
})

七、变量插值

configparser 支持在配置文件中使用变量插值,语法为 %(variable_name)s

[paths]
home_dir = /home/user
config_dir = %(home_dir)s/config

在读取 config_dir 时,%(home_dir)s 会被替换为 /home/user

八、完整示例

以下是一个完整的示例,展示了如何使用 configparser 模块读取和写入配置文件:

import configparser

# 创建配置对象
config = configparser.configparser()

# 读取配置文件
config.read('example.ini', encoding='utf-8')

# 获取所有节
print(config.sections())

# 获取某个节的所有配置项
print(config.items('section_name'))

# 获取某个配置项的值
value = config.get('section_name', 'option_name')
print(value)

# 添加新的节和配置项
config.add_section('new_section')
config.set('new_section', 'new_option', 'value')

# 写入配置文件
with open('example.ini', 'w', encoding='utf-8') as configfile:
    config.write(configfile)

以上就是python使用configparser模块管理ini格式配置文件的详细内容,更多关于python configparser管理配置文件的资料请关注代码网其它相关文章!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2026  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com