博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

configparser mode

Posted on 2020-04-26 23:08  moss_tan_jun  阅读(134)  评论(0编辑  收藏  举报

# python doc

https://www.cnblogs.com/june-L/category/1586901.html

一、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对象执行的一些修改操作,必须重新写回到文件才可生效

示例:

[first]
name="yusheng_liang"
age=20
sex = "man"

[second]
name="june"
age=25
sex = "weman"

 

==

#!/usr/bin/env python
# -*- coding:utf-8 -*-

import configparser

con = configparser.ConfigParser()
#con对象的read功能,打开文件读取文件,放进内存
con.read("default.txt", encoding='utf-8')

#1、con对象的sections,内存中所有的节点
result = con.sections()
print("所有的节点:", result)

#2、获取指定节点下的所有键值对
con_items = con.items("first")
print('first下所有的键值对:', con_items)

#3、获取指定节点下的所有键
ret = con.options("second")
print('second下的所有键:', ret)

#4、获取指定节点下指定的key的值
v = con.get("second", 'age')
print('second节点下age的值:', v)

#5、检查、删除、添加节点
#5.1检查是否存在指定的节点,返回True为存在,False为不存在
has_con = con.has_section("first")
print('是否已存在first节点:', has_con)
#5.2添加节点
con.add_section("SEC-1")
#con.write(open('default.txt', 'w'))
#5.3删除节点
con.remove_section("SEC-1")
#con.write(open('default.txt', 'w'))

#6、检查、删除、设置指定组内的键值对
#6.1检查
has_opt = con.has_option('second', 'age')
print(has_opt)
#6.2删除
con.remove_option('second', 'age')
#6.3设置
con.set('second', 'name', "june_liang")
#对configparser对象执行的一些修改操作,必须重新写回到文件才可生效
con.write(open('default.txt', 'w'))