configparser.ConfigParser使用

self.conf 是 configparser.ConfigParser 的实例对象,用于管理 .ini 格式的配置文件。其核心用法涵盖配置的读写、修改、类型转换等场景,具体如下:

一、读取配置‌

获取字符串值‌

value = self.conf.get("section", "key")  # 返回字符串类型值‌:ml-citation{ref="1,3" data="citationList"}

获取数值类型值‌

port = self.conf.getint("database", "port")  # 返回整数‌:ml-citation{ref="1,6" data="citationList"}
ratio = self.conf.getfloat("settings", "ratio")  # 返回浮点数‌:ml-citation{ref="6,8" data="citationList"}

获取布尔值‌

debug = self.conf.getboolean("logging", "debug")  # 返回 True/False‌:ml-citation{ref="1,6" data="citationList"}

获取整个 Section 的键值对‌

items = self.conf.items("section_name")  # 返回元组列表,如 [("key1", "value1"), ...]‌:ml-citation{ref="1,8" data="citationList"}

二、修改与写入配置‌

新增 Section‌

self.conf.add_section("new_section")  # 添加空 Section‌:ml-citation{ref="1,5" data="citationList"}

设置键值对‌

self.conf.set("section", "key", "value")  # 存在则修改,不存在则新增‌:ml-citation{ref="1,4" data="citationList"}

删除配置项‌

self.conf.remove_option("section", "key")  # 删除指定键‌:ml-citation{ref="1,5" data="citationList"}
self.conf.remove_section("section")  # 删除整个 Section‌:ml-citation{ref="1,5" data="citationList"}

保存到文件‌

with open("config.ini", "w") as f:
    self.conf.write(f)  # 将修改后的配置写入文件‌:ml-citation{ref="1,4" data="citationList"}

三、其他操作‌

检查 Section 或 Key 是否存在‌

has_section = self.conf.has_section("section")  # 返回布尔值‌:ml-citation{ref="1,8" data="citationList"}
has_key = self.conf.has_option("section", "key")  # 返回布尔值‌:ml-citation{ref="1,8" data="citationList"}

获取所有 Section 名称‌

sections = self.conf.sections()  # 返回列表,如 ["section1", "section2"]‌:ml-citation{ref="1,8" data="citationList"}

处理默认值‌

# 若 Key 不存在,返回默认值
value = self.conf.get("section", "key", fallback="default_value"):ml-citation{ref="6,8" data="citationList"}

保留键的大小写‌

# 初始化时设置参数,避免 Key 被自动转为小写
self.conf = configparser.ConfigParser(allow_no_value=True, inline_comment_prefixes=(";",)):ml-citation{ref="1,5" data="citationList"}

四、典型示例‌

# 初始化配置解析器
self.conf = configparser.ConfigParser()
self.conf.read("config.ini")
# 读取数据库配置
host = self.conf.get("database", "host")  # 字符串‌:ml-citation{ref="1,3" data="citationList"}
port = self.conf.getint("database", "port")  # 整数‌:ml-citation{ref="6,8" data="citationList"}

# 新增日志配置
self.conf.add_section("logging"):ml-citation{ref="1,5" data="citationList"}
self.conf.set("logging", "level", "INFO"):ml-citation{ref="1,4" data="citationList"}

# 检查并保存
if self.conf.has_section("database"):
    with open("config.ini", "w") as f:
        self.conf.write(f):ml-citation{ref="1,4" data="citationList"}

五、注意事项‌
文件编码‌:建议使用 encoding 参数指定文件编码,避免乱码:

self.conf.read("config.ini", encoding="utf-8"):ml-citation{ref="3,6" data="citationList"}

键名大小写‌:默认会将键名转为小写,需通过初始化参数控制‌。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值