ini文件如下
1. 导入 configparser
import configparser
2.创建对象 打开文件
cf = configparser.ConfigParser() # 创建管理对象
cf.read('test.ini', encoding='utf-8') # 读取ini文件
3. 读
(1) 获取所有section
sections = cf.sections() # 获取所有的section
print(sections) # 返回一个列表list
print(sections[0])
# 输出 ['qq', 'weixin']
# 输出 qq
(2) 获取具体某一个section内的内容
items = cf.items('qq')
print(items)
print(items[0])
print(items[0][0])
# 输出 [('a', '1'), ('b', '2')] # 打印出为字典
# 输出 ('a', '1') # 打印出为元组
# 输出 a
4. 增
(1) 新增一个section
cf.add_section('aaa')
print(cf.sections())
# 输出 ['qq', 'weixin', 'aaa']
(2) 新增一个key和value
cf.set('aaa', 'c', '256')
items = cf.items('aaa')
print(items)
# 输出 [('c', '256')]
5. 删除 remove
(1) 删除section
cf.remove_section('qq')
print(cf.sections())
# 输出 ['weixin']
(2) 删除指定key
cf.remove_option('qq', 'a')
items = cf.items('qq')
print(items)
# 输出 [('b', '3')]
6. write写入
1.write写入有两种方式,一种是删除原文件内容,重新写入:w
cf.write(open(cfgpath, “w”)) # 删除原文件重新写入
2.另外一种是在原文件基础上继续写入内容,追加模式写入:a
cf.write(open(cfgpath, “a”)) # 追加模式写入
参考:
https://blog.csdn.net/zhusongziye/article/details/80024530