day016-python-configparser模块,configparser


一、configparser介绍
configparser模块主要用于读取配置文件,导入方法:import configparser

二、基本操作

2.1、获取节点sections
ConfigParserObject.sections()
以列表形式返回configparser对象的所有节点信息

2.2、获取指定节点的的所有配置信息
ConfigParserObject.items(section)
以列表形式返回某个节点section对应的所有配置信息

2.3、获取指定节点的options
ConfigParserObject.options(section)
以列表形式返回某个节点section的所有key值

2.4、获取指定节点下指定option的值
ConfigParserObject.get(section, option)
返回结果是字符串类型
ConfigParserObject.getint(section, option)
返回结果是int类型
ConfigParserObject.getboolean(section, option)
返回结果是bool类型
ConfigParserObject.getfloat(section, option)
返回结果是float类型

2.5、检查section或option是否存在
ConfigParserObject.has_section(section)
ConfigParserObject.has_option(section, option)
返回bool值,若存在返回True,不存在返回False

2.6、添加section
ConfigParserObject.add_section(section)
如果section不存在,则添加节点section;
若section已存在,再执行add操作会报错configparser.DuplicateSectionError: Section XX already exists

2.7、修改或添加指定节点下指定option的值
ConfigParserObject.set(section, option, value)
若option存在,则会替换之前option的值为value;
若option不存在,则会创建optiion并赋值为value

2.8、删除section或option
ConfigParserObject.remove_section(section)
若section存在,执行删除操作;
若section不存在,则不会执行任何操作
ConfigParserObject.remove_option(section, option)
若option存在,执行删除操作;
若option不存在,则不会执行任何操作;
若section不存在,则会报错configparser.NoSectionError: No section: XXX

2.9、写入内容
ConfigParserObject.write(open(filename, 'w'))
对configparser对象执行的一些修改操作,必须重新写回到文件才可生效

示例:

配置文件default.txt

1 [first]
2     name="yusheng_liang"
3     age=20
4     sex = "man"
5 
6 [second]
7     name="june"
8     age=25
9     sex = "weman"

python代码实现:

1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 4 import configparser 5 6 con = configparser.ConfigParser() 7 #con对象的read功能,打开文件读取文件,放进内存 8 con.read("default.txt", encoding='utf-8') 9 10 #1、con对象的sections,内存中所有的节点 11 result = con.sections() 12 print("所有的节点:", result) 13 14 #2、获取指定节点下的所有键值对 15 con_items = con.items("first") 16 print('first下所有的键值对:', con_items) 17 18 #3、获取指定节点下的所有键 19 ret = con.options("second") 20 print('second下的所有键:', ret) 21 22 #4、获取指定节点下指定的key的值 23 v = con.get("second", 'age') 24 print('second节点下age的值:', v) 25 26 #5、检查、删除、添加节点 27 #5.1检查是否存在指定的节点,返回True为存在,False为不存在 28 has_con = con.has_section("first") 29 print('是否已存在first节点:', has_con) 30 #5.2添加节点 31 con.add_section("SEC-1") 32 #con.write(open('default.txt', 'w')) 33 #5.3删除节点 34 con.remove_section("SEC-1") 35 #con.write(open('default.txt', 'w')) 36 37 #6、检查、删除、设置指定组内的键值对 38 #6.1检查 39 has_opt = con.has_option('second', 'age') 40 print(has_opt) 41 #6.2删除 42 con.remove_option('second', 'age') 43 #6.3设置 44 con.set('second', 'name', "june_liang") 45 #对configparser对象执行的一些修改操作,必须重新写回到文件才可生效 46 con.write(open('default.txt', 'w')) View Code

 

相关内容

    暂无相关文章

评论关闭