python解析配置文件---configparser模块

1.configparser模块介绍

configparser是用来读取配置文件的模块,配置文件格式为:中括号“[ ]”内包含的为section。section 下面为类似于key-value 的配置内容。

 

a.conf的文件内容如下:

[user01]
name = user01
is_admin = True
age = 34
passwd = user123456

[yxwang]
name = yxwang
age = 25
passwd = 123456

取值:

import configparser
#取值
config=configparser.ConfigParser()  #调用condigparser下的ConfigParser的方法,得到一个对象
config.read('a.conf')  #写上配置文件的路径,打开文件.
print(config.sections())  #得到配置文件中的标题。  #['user01', 'yxwang']
print(config.options(config.sections()[0])) #查看某个标题下的配置项 等同于获取user01下的配置项的key
res=config.get('user01','passwd')#查看某个标题下的某个配置项的值  注意这样得到的数值是字符串类型

res1=config.getint('user01','age') #这样得到的数值是一个字符串.

res1=config.getboolean('user01','is_admin') #这样得到的数值是一个布尔值.
print(res)

修改:

import configparser
config=configparser.ConfigParser()  #调用condigparser下的ConfigParser的方法,得到一个对象
config.read('a.conf')  #写上配置文件的路径,打开文件.

config.remove_section('yxwang')  #删除一个标题,标题删除了标题下的内容也一并删除了
config.remove_option('user01','age') #删除一个标题下的内容

config.add_section('user03')  #新增一个标题
config.set('user03','name','user03')  #为指定标题插入内容


config.write(open('a.conf','w')) #写入文件

 

posted @ 2017-08-20 18:05  嘟囔囔小孩  阅读(254)  评论(0编辑  收藏  举报