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动态类型的学习---引用的理解
- Python3写爬虫(四)多线程实现数据爬取
- 垃圾邮件过滤器 python简单实现
- 下载并遍历 names.txt 文件,输出长度最长的回文人名。
- install and upgrade scrapy
- Scrapy的架构介绍
- Centos6 编译安装Python
- 使用Python生成Excel格式的图片
- 让Python文件也可以当bat文件运行
- [Python]推算数独
- Python中zip()函数用法举例
- Python中map()函数浅析
- Python将excel导入到mysql中
- Python在CAM软件Genesis2000中的应用
- 使用Shiboken为C++和Qt库创建Python绑定
- FREEBASIC 编译可被python调用的dll函数示例
- Python 七步捉虫法