configparser 配置文件模块----day19

configparser 配置文件
读取配置信息 两步
1.读取某个配置文件
2.调用get函数

# 作为配置文件 最常用的操作就是读取 很少会做修改
# 总结: read读取配置文件
# add_section 添加分区
# set 如果没有这个选项则添加
# remove_section 删除分区
# remove_option 删除选项


cfg= configparser.ConfigParser()--创建一个配置文件解释器
cfg.read("test.cfg",encoding="UTF-8")--读取一个名为test.cfg的配置文件
print(cfg.sections())--获取分区

username = cfg.get("mysql","username")--获取某个分区下的某个选项 第一个参数分区名 第二个选项名称
password = cfg.get("mysql","password")--同上取值后付给要进用的变量

cfg.getfloat()--浮点型
cfg.getint()----整型
cfg.getboolean()--布尔

修改--先读取文件---->在修改--->在写入文件
cfg=confingparser.ConfigParser()
cfg.read("test.cfg",encoding="utf-8")----从一个文件中读取值

将mysql分区下的lock改为True
cfg.set("mysql","lock","true")

with open("test.cfg","wt",encoding="UTF-8") as f:
cfg.write(f)

# -------------添加新的选项 port 值为3306----------------
cfg = configparser.ConfigParser()
cfg.read("test.cfg",encoding="utf-8")

# ------------添加新的分区
cfg.add_section("新分区")
# ------------添加新的选项 port 值为3306
cfg.set("mysql","port","3306")

# 删除---整个文件
cfg = configparser.ConfigParser()
cfg.read("test.cfg",encoding="utf-8")

# 删除分区
cfg.remove_section("新分区")
# 删除某个分区的选项
cfg.remove_option("mysql","port")

# 判断是否存在某个分区-返回Ture
print(cfg.has_section("mysql"))
# 判断是否存在某个选项-返回Ture
print(cfg.has_option("mysql","username"))

猜你喜欢

转载自www.cnblogs.com/wenchen/p/10096908.html
今日推荐