1 import configparser
2 #创建ConfigParser对象
3 config = configparser.ConfigParser()
4 # #创建配置文件
5 config["DEFAULT"]={"aa":"bb","cc":"dd","ee":"ff"}
6 # #创建文件对象,并保存
7 #
8 con = config["www.baidu.com"]={}
9 config["www.baidu.com"]["user"] ="xiaohua"
10 #
11 config["www.yahu.com"]={}
12 yahu = config["www.yahu.com"]
13 yahu["yh"]="www.ya.com"
14 yahu["hu"]="www.hu.com"15 with open("config.ini","w",encoding="utf8") as ff:
16 config.write(ff)
1 #读取文件内容
2 config.read("config.ini".encode("utf8"))
3 print(config.sections())
4 print(config.defaults())
5 print(config["www.yahu.com"]["yh"])
6 cc = config["www.yahu.com"]
7 print(cc["yh"])
8 for i in config["www.baidu.com"]:
9 print(i) #默认(DEFAULT)也会被打印
10 print(config["www.baidu.com"][i]) #取值
#删除块
config.remove_section("www.baidu.com")
with open("config.ini","w",encoding="utf8") as cctv:
config.write(cctv)
#删除键值对
config.remove_option("www.yahu.com","hu")
with open("config.ini","w",encoding="utf8") as cctv:
config.write(cctv)
#修改
config.set("www.yahu.com","hu","hhhh") #从左到右依次块,块下面的键,要修改的值
with open("config.ini","w",encoding="utf8") as cctv:
config.write(cctv)