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(f'nworkers is: {cfg.getint("server", "nworkers")}')
print(f'signature is: {cfg.get("server", "signature")}')
运行结果会显示各个分区的名称以及对应的值。这里特别留意一下类型转换方法,比如 getboolean 和 getint,它们能直接返回布尔或整数,省去了手动转换的麻烦。ConfigParser 还会自动处理变量替换,所以 %(prefix)s 会被展开为实际路径。
修改配置
修改配置相对简单,但要注意内存与磁盘的区别。set 方法只修改内存中的对象,不会立即写入文件。
# 修改内存中的值
cfg.set('server', 'port', '9000')
cfg.set('debug', 'log_errors', 'False')
print(f'new debug is: {cfg.getboolean("debug", "log_errors")}')
print(f'After change, port is: {cfg.getint("server", "port")}')
# 注意:如果不调用 cfg.write(),文件本身不会被更新
另外,INI 文件的 Key 不区分大小写这一点在实际使用中很有用。例如:
print(cfg.get('installation', 'PREFIX'))
print(cfg.get('installation', 'prefix'))
无论大写还是小写,都能正确获取到 /usr/local。如果需要在实际项目中持久化修改,记得在修改后打开文件并调用 cfg.write() 将数据写回。

