python学习之 - configparser模块

configparser模块
功能:用于生成和修改常见配置文件。
基本常用方法如下:

read(filename):直接读取配置文件
write(filename):将修改后的配置文件写入文件中。
defaults():返回全部示例中所有defaults
sections():得到所有的section,并以列表的形式返回
items(section):得到该section的所有键值对
has_section(section):检查是否有section,有返回True,无返回False
has_option(section,option):检查section下是否有指定的option,有返回True,无返回False
getint(section,option):得到section中option的值,返回为int类型
get(section,option):得到section中option的值,返回为string类型
getboolean(section,option):得到section中option的值,返回为boolean类型
getfloat(section,option):得到section中option的值,返回为float类型
add_section(section):添加一个新的section
remove_section(section):删除某个section
options(section):得到该section的所有option
set(section,option,value):对section中的option进行设置,需要调用write将内容写入配置文件
remove_option(section,option):删除某个section下的option


能处理的配置文件格式如下:
[mysql] #节点名
键 = 值
举例1:自动生成一个配置文件
 1 import configparser
 2 # 自动生成配置文件
 3 cfg = configparser.ConfigParser()
 4 # 创建一个全局配置
 5 cfg['DEFAULT'] = {
 6     'ServerAliveInterval':'45',
 7     'Compression':'yes',
 8     'CompressionLevel':'9'
 9 }
10 #创建局部配置
11 cfg['bitbucket.org'] = {}
12 cfg['bitbucket.org']['User'] = 'hg'
13 cfg['topsecret.server.com'] = {}
14 topsecret = cfg['topsecret.server.com']
15 topsecret['host port'] = '50022'
16 topsecret['ForwardX11'] = 'no'
17 cfg['DEFAULT']['ForwardX11'] = 'yes'
18 # 配置完成,重写文件
19 with open('example.ini','w') as f:
20     cfg.write(f)
View Code
###以下进行配置文件的 增/删/改/查 功能实例
先导入模块读取配置文件
import configparser
cfg = configparser.ConfigParser()
# 读取配置文件
cfg.read('example.ini',encoding='utf-8')
# 提取所有第一层节点信息以列表打印
info = cfg.sections()
print(info)
-- 增 操作
# 判断节点是否存在
sec = cfg.has_section('name')
# 判断节点下的text键是否存在
sec = cfg.has_option('name','text')
# 增加节点操作
sec = cfg.add_section('name')
View Code
-- 修改/增加 为节点增加或修改一行数据 操作
cfg.set('name','text','jeck')
cfg.write(open('examp2.ini','w'))
View Code
-- 删 操作
# 删除bitbucket.org节点所有数据
sec = cfg.remove_section('bitbucket.org')
cfg.write(open('examp1.ini','w'))
# 删除节点下一行数据
sec = cfg.remove_option('topsecret.server.com','host port')
cfg.write(open('examp2.ini','w'))
View Code
-- 查 操作
# 单独打印default信息
print(cfg.defaults())
#  以元组列表形式打印指定节点下所有信息(会连带默认打印default信息)
print(cfg.items('bitbucket.org'))
# 查找打印匹配信息
print(cfg['bitbucket.org']['user']) 类似于 print(cfg.get('bitbucket.org','user'))
print(cfg['DEFAULT']['forwardx11'])
section_name = cfg.sections()[1]
print(cfg[section_name]['host port'])
# 循环打印指定节点下所有信息
for k,v in cfg[section_name].items():
    print(k,v)

# 打印指定节点和默认节点所有的Key
 print(cfg.options('topsecret.server.com'))
 for k,v in cfg.items('topsecret.server.com'):
     print(k,v)
View Code

 

posted @ 2017-05-11 17:11  十年如一..bj  阅读(187)  评论(0编辑  收藏  举报