from configparser import ConfigParser
string ="""
[DEFAULT]
like="吃北京烤鸭"
ect="喝青岛啤酒"
[two]
name="张三"
age="15"
like="吃烤鸭"
"""
cfg = ConfigParser()
cfg.read_string(string)#遍历for i in cfg:print(i)for k,v in cfg.items(i):print(k,":",v)print()#写入配置文件withopen("gdy.ini","w",encoding="utf-8")as f:
cfg.write(f)
输出结果为:
read_dict(dictionary,source="") #从字典中读取ini配置信息
dictionary:字典类型的ini配置信息
source:
简单示例:
from configparser import ConfigParser
dt ={"DEFAULT":{"like":"打篮球","ect":"吃北京烤鸭"},"mysql":{"name":"张三","age":16}}
cfg = ConfigParser()#从字典种读取ini配置信息
cfg.read_dict(dt)#遍历for i in cfg:print(i)for k,v in cfg.items(i):print(k,":",v)print()#写入配置文件withopen("gdy.ini","w",encoding="utf-8")as f:
cfg.write(f)
defitems(self, section=_UNSET, raw=False,vars=None):"""Return a list of (name, value) tuples for each option in a section.
All % interpolations are expanded in the return values, based on the
defaults passed into the constructor, unless the optional argument
`raw' is true. Additional substitutions may be provided using the
`vars' argument, which must be a dictionary whose contents overrides
any pre-existing defaults.
The section DEFAULT is special.
"""if section is _UNSET:returnsuper().items()
d = self._defaults.copy()try:
d.update(self._sections[section])except KeyError:if section != self.default_section:raise NoSectionError(section)# Update with the entry specific variablesifvars:for key, value invars.items():
d[self.optionxform(key)]= value
value_getter =lambda option: self._interpolation.before_get(self,
section, option, d[option], d)if raw:
value_getter =lambda option: d[option]return[(option, value_getter(option))for option in d.keys()]
简单综合示例:
from configparser import ConfigParser
string ="""
[DEFAULT]
like="吃北京烤鸭"
ect="喝青岛啤酒"
[two]
name="张三"
age="15"
like="吃烤鸭"
[one]
name = "李四"
age = "18"
show = "跳舞"
"""
cfg = ConfigParser()
cfg.read_string(string)
sct = cfg.sections()print("执行方法sections(),返回值类型",type(sct),"返回值:",sct)print("----------------")print("开始测试options()")for i in sct:
op = cfg.options(i)#注意options返回key中会包含默认的keyprint(type(op),op)print("-----------------------")print("开始测试get")print(cfg.get("one","name"),cfg.get("one","ect"))print("------------------")print("开始测试items()")
itm = cfg.items()print(type(itm),itm)for i in itm:print(i)for k in i[1]:print("\t",k)print("----------------------")print("开始测试items(section)")
secitm = cfg.items("one")print(type(secitm),secitm)for i in secitm:print(i)