[www]
gender = 0
[ccc]
age = 19
gender = man
[yyy]
引入“configparser” 包
调用Configpaser 类
思路就是先读取文件,section(部分),读取文件[xxx]内容
con = configparser.ConfigParser()
#con 对象的read功能,打开文件读取文件,放进内容
con.read('ini',encoding='utf-8')
#寻找文件中[xxx]内容的文件
result = con.sections()
print(result)
>>>
['www', 'ccc']
items 获取指定节点下所有的键值对
ret =con.items("www")
print(ret)
>>>
[('age', '123'), ('gender', '0')]
opitons 获取指定节点下所有的键
ret1 = con.options("www")
print(ret1)
>>>
['age', 'gender']
get获取指定节点下的key
v=con.get("www","age")
print(v)
>>>
123
has_section 检查节点是否存在返回 True False
has_www=con.has_section("www")
print(has_www)
>>>
True
添加节点add_section
con.add_section("yyy")
con.write(open("ini","w"))
删除节点remove_section
con.remove_section("www")
#删除节点下内容
con.remove_option("www","age")
con.write(open("ini","w"))
检查、删除、设置指定组内的键值对
import configparser
config = configparser.ConfigParser()
config.read('xxxooo', encoding='utf-8')
# 检查
has_opt = config.has_option('section1', 'k1')
print(has_opt)
# 删除
config.remove_option('section1', 'k1')
config.write(open('xxxooo', 'w'))
# 设置
config.set('section1', 'k10', "123")
config.write(open('xxxooo', 'w'))