INI 配置文件基础
INI 文件在脚本和工具程序中非常常见,结构清晰,适合存储简单的键值对配置。需要注意的是,ConfigParser 默认情况下 Key 是不区分大小写的。
示例配置文件
假设我们有一个 test.ini 文件,内容如下:
[installation]
library=%(prefix)s/lib
include=%(prefix)s/include
bin=%(prefix)s/bin
prefix=/usr/local
[debug]
log_errors=true
show_warnings=False
[server]
port=8080
nworkers=32
pid-file=/tmp/spam.pid
root=/www/root
signature=Brought to you by the Python Cookbook
读取与解析
使用 configparser 模块可以方便地处理这类文件。下面是一个完整的读取示例:
from configparser import ConfigParser
cfg = ConfigParser()
cfg.read('test.ini')
# 获取所有分区名称
print(f'sections is: {cfg.sections()}')
# 获取字符串值
print(f'library is: {cfg.get("installation", "library")}')
# 自动转换类型
print(f'log errors: {cfg.getboolean("debug", "log_errors")}')
print(f'port is: {cfg.getint("server", "port")}')
print()
()

