标签:items alt group art gate man 读取 bubuko 技术分享
配置文件:conf.ini
[DEFAULT]
name = gudon[company_info]
company = fesco
fesid = 99891234[department_info]
position = system manager
addr = south of the gate 14
import configparser
conf = configparser.ConfigParser()
conf.read("conf.ini")
print(conf.sections()) # [‘company_info‘, ‘department_info‘]
print(conf.default_section) # DEFAULT
print(conf["company_info"]["company"]) # fesco
for k, v in conf["company_info"].items():
print(k, v)
# company fesco
# fesid 99891234
# name gudon [DEFAULT]中的内容是会在下面的所有节点里面都包含,此处需注意
# 判断fesid 是否在 配置文件中
if "fesid" in conf["company_info"]:
print(conf["company_info"]["fesid"]) # 99891234
配置文件 conf2.ini
支持的两种分隔符“=”, “:”
[group1] k1 = v1 k2:v2 [group2] k1 = v1
import configparser
conf = configparser.ConfigParser()
conf.read("conf2.ini")
print(conf.options("group1")) # [‘k1‘, ‘k2‘]
print(conf["group1"]["k2"]) # v2
# 添加
conf.add_section("group3")
conf["group3"]["name"] = "Kinus"
conf["group3"]["age"] = "22"
conf.set("group2", "k1", "1111") # 此处会将group2 中的 k1 的值改为1111
conf.set("group2", "k2", "2222") # 此处会在group2中新增一个 k2 = 2222
conf.write(open("conf3.ini","w"))
添加后新生成的 conf3.ini:
删除配置文件中的内容:
import configparser
conf = configparser.ConfigParser()
conf.read("conf2.ini")
# 删除
conf.remove_option("group1", "k2")
conf.remove_option("group2", "k1")
conf.write(open("conf4.ini", "w"))
标签:items alt group art gate man 读取 bubuko 技术分享
原文地址:https://www.cnblogs.com/friday69/p/9280624.html