其他分享
首页 > 其他分享> > configparser.ConfigParser

configparser.ConfigParser

作者:互联网

这是fens.conf里的初始内容:

 

 


下面是python3中configparser的处理原码:
import configparser
cf = configparser.ConfigParser()
cf.read(“/Users/macxunlei/Desktop/python3/配置文件/config1.conf”)
s = cf.sections() ====>[‘ybp’,’cz’]
o1 = cf.options(“ybp”)====>[‘name’, ‘age’, ‘tel’, ‘address’]
o2 = cf.options(“cz”)====>[‘name’, ‘age’, ‘tel’, ‘address’]

i1 = cf.items(“ybp”)===>[(‘name’, ‘Tester杨’), (‘age’, ‘24’), (‘tel’, ‘18520374632’),(‘address’, ‘安徽阜阳’)]
i2 = cf.items(“cz”)===>[(‘name’, ‘Qianduan陈’), (‘age’, ‘25’), (‘tel’, ‘18629072893’), (‘address’, ‘安徽滁州’)]

i1_name_value = cf.get(“ybp”,”name”) ====> ‘Tester杨’
i1_age_int_value = cf.getint(“ybp”,”age”) ===> 24
i1_age_value = cf.get(“ybp”,”age”) ===> ‘24’
i1_tel_int_value = cf.getint(“ybp”,”tel”) ====> 18520374632
i1_tel_value = cf.get(“ybp”,”tel”) =====> ‘18520374632’
i1_address_value = cf.get(“ybp”,”address”) ====> ‘安徽阜阳’

if cf.has_section(“yb”):
print(“有了yb了!”)
else :
print(“没有sale袁!!现在开始写入:”)
cf.add_section(“yb”)
cf.set(“yb”,”name”,”sale袁”)
cf.set(“yb”,”age”,”27”)
cf.set(“yb”,”tel”,”182903865”)
cf.set(“yb”,”address”,”湖北岳阳”)#现在只是在内存中,可以查看到,但是没有写到文件中
cf.write(open(“/Users/macxunlei/Desktop/python3/配置文件/config1.conf”,”w”))

下面是删除、修改的操作:
(1) 删除selection
if cf.has_section(“s1”):
cf.remove_section(“s1”)
cf.write(open(“a.conf”,”w”))
(2) 删除option
if cf.has_option(“s1”,”o”):
cf.remove_option(“s1”,”o”);
cf.write(open(“a.conf”,”w”))
(3) 修改option
使用set()和新增加一样,这里不再写了
cf.set(“s1”,”option1”,”新值”)
cf.write(open(“a.conf”,”w”))

 

标签:tel,name,ybp,age,yb,cf,ConfigParser,configparser
来源: https://www.cnblogs.com/gangtie/p/16462269.html