python 读取自己的配置

来源:互联网 发布:素材软件 编辑:程序博客网 时间:2024/03/29 20:57

    python中,如果要程序读取自己的配置文件,则要用到configparser

 这个库能让自己的脚本,去读取相关的配置文件


1 导入configparser

import configparsercf = configparser.ConfigParser()cf.read("cong.ini")
2 读取相关的
s = cf.sections()print("section:",s)

3 获取 options
o1 = cf.options("mysql")print("options:mysql",o1)

3 获取items 
v1 = cf.items("mysql")print("items:mysql",v1)
4 获取相关值
host = cf.get("mysql","host")
t1= cf['mysql']['host']

5 增加判断逻辑
新增section
if cf.has_section("mysql"):    print("有了 [mysql] 了!")else :    print("没有 [mysql] !!现在开始写入:")    cf.add_section("mysql")    cf.set("mysql","addd1","addd1的值")    cf.set("mysql","addd2","addd2的值")    cf.write(open("cong.ini","w"))    print("[addd] 写入完成")


删除section
if cf.has_section("xxxx"):    print("有 [xxxx] 了,开始删除:")    cf.remove_section("xxxx")    cf.write(open("cong.ini","w"))    print("删除 [xxxx] 成功")else:    print("没有[xxxx],不需处理!")


0 0
原创粉丝点击