您的位置:首页 > 编程语言 > Python开发

python-ConfigParser模块学习

2015-10-16 09:37 567 查看

介绍

ConfigParser模块在python中是用来读取配置文件,配置文件的格式跟windows下的
ini
配置文件相似,可以包含一个或多个节(section),每个节可以有多个参数(键=值)。使用的配置文件的好处就是不用再程序中硬编码,可以是你的程序变得灵活起来。

注意:在python 3 中
ConfigParser
模块名已更名为
configparser


函数

读取配置文件

read(filename) 直接读取ini文件内容

sections() 得到所有的section,并以列表的形式返回

options(section) 得到该section的所有option

items(section) 得到该section的所有键值对

get(section,option) 得到section中option的值,返回为string类型

getint(section,option) 得到section中option的值,返回为int类型

getfloat(section,option)得到section中option的值,返回为float类型

getboolean(section, option)得到section中option的值,返回为boolean类型

写入配置文件

add_section(section) 添加一个新的section

has_section(section) 判断是否有section

set( section, option, value) 对section中的option进行设置

remove_setion(section)删除一个section

remove_option(section, option)删除section中的option

write(fileobject)将内容写入配置文件。

使用

配置文件
config.ini
如下:

[user]
username = tom
password = ***
email = test@host.com

[book]
bookname = python
bookprice = 25


注意:也可以使用
:
替换
=


程序:

# -* - coding: UTF-8 -* -
import ConfigParser
import sys

reload(sys)
sys.setdefaultencoding("utf-8")

#生成config对象
conf = ConfigParser.ConfigParser()
#用config对象读取配置文件
conf.read("config.ini")
#以列表形式返回所有的section
sections = conf.sections()
print 'sections:', sections   #sections: ['user', 'book']
#得到指定section的所有option
options = conf.options("user")
print 'options:', options  #options: ['username', 'password', 'email']
#得到指定section的所有键值对
useritem = conf.items("user")
print 'user:', useritem #user: [('username', 'tom'), ('password', '***'), ('email', 'test@host.com')]
#指定section,option读取值
str_val = conf.get("book", "bookname")
int_val = conf.getint("book", "bookprice")

print "value for book's bookname:", str_val   #value for book's bookname: python
print "value for book's bookprice:", int_val   #value for book's bookprice: 25

#写配置文件
#更新指定section,option的值
conf.set("book", "bookname", "python learning")
#写入指定section增加新option和值
conf.set("book", "bookpress", u"人民邮电出版社")
#增加新的section
conf.add_section('purchasecar')
conf.set('purchasecar', 'count', '1')
#写回配置文件
conf.write(open("config.ini", "w"))


参考:

1. https://docs.python.org/2/library/configparser.html

2. http://blog.csdn.net/gexiaobaohelloworld/article/details/7976944
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python config parser