在 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)
369

被折叠的 条评论
为什么被折叠?



