Python configparser模块的使用
Python configparser模块的使用
先创建一个txt文件,输入以下文本后,可以命名为config.ini
[first] name = XiaoHua age = 20 sex = "man" [second] name = Xiao_Hong age = 17 sex = "woman"
创建py程序测试
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import configparser
con = configparser.ConfigParser() #con对象的read功能,打开文件读取文件,放进内存
con.read("config.ini", encoding='utf-8')
result = con.sections() #1、con对象的sections,内存中所有的节点
print("所有的节点:", result)
con_items = con.items("first") #2、获取指定节点下的所有键值对
print('first下所有的键值对:', con_items)
ret = con.options("second") #3、获取指定节点下的所有键
print('second下的所有键:', ret)
v = con.get("second", 'age') #4、获取指定节点下指定的key的值
print('second节点下age的值:', v)
#5、检查、删除、添加节点
has_con = con.has_section("first") #5.1检查是否存在指定的节点,返回True为存在,False为不存在
print('是否已存在first节点:', has_con)
con.add_section("SEC-1") #5.2添加节点 如果已有会报错
#con.write(open('default.txt', 'w'))
con.remove_section("SEC-1") #5.3删除节点
#con.write(open('default.txt', 'w'))
#6、检查、删除、设置指定组内的键值对
has_opt = con.has_option('second', 'age') #6.1检查节点的键
print(has_opt)
con.remove_option('second', 'age') #6.2删除节点的键
con.set("second",'age','17') #6.3添加age 并设置键值为17
con.set('first', 'name', "XiaoHua") #6.4设置键值
con.write(open('config.ini', 'w')) #对configparser对象执行的一些修改操作,必须重新写回到文件才可生效
运行结果:


浙公网安备 33010602011771号