ConfigParser模块学习

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)将内容写入配置文件。

import configparser
config = configparser.ConfigParser() config['DEFAULT'] = {'ServerALiveInterval': '',
'Compression': 'yes',
'CompressionLevel': ''}
config['bitbucket.org'] = {}
config['bitbucket.org']['User'] = 'hg'
config['topsecret.server.com'] = {}
topsecret = config['topsecret.server.com']
topsecret['Host Port'] = ''
topsecret['ForwardXll'] = 'no'
config['DEFAULT']['ForwardXll'] = 'yes' with open('example.ini','w') as configfile:
config.write(configfile)
[DEFAULT]
serveraliveinterval = 45
compression = yes
compressionlevel = 9
forwardxll = yes [bitbucket.org]
user = hg [topsecret.server.com]
host port = 50022
forwardxll = no

配置文件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. CSS学习笔记
  2. iOS中支付宝集成
  3. Java优先队列
  4. SwipeRefreshLayout + RecyclerView 实现 上拉刷新 和 下拉刷新
  5. Python: 安装BeautifulSoup4
  6. Linux 远程和本地的一些解决方案
  7. Noip模拟考第三题——饥饿游戏
  8. CentOS7安装配置FTP服务器
  9. Codeforces243C-Colorado Potato Beetle(离散化+bfs)
  10. JS中的逻辑哲学
  11. idea为tomcat设置虚拟地址
  12. python Django之文件上传
  13. Grid move
  14. T-SQL流程控制语句
  15. poj2373 Dividing the Path (单调队列+dp)
  16. poj2481
  17. JS选取DOM元素的方法
  18. Windows Installer服务总是自动关闭导致无法安装在win10上安装英伟达显卡驱动的解决方案
  19. [Luogu4899][IOI2018] werewolf 狼人
  20. 小计---pandas读取带有中文文件名或者包含中文内容的文件

热门文章

  1. 接着继续(OO博客第四弹)
  2. CMD命令操作符
  3. 课堂练习 psp表
  4. 软工实践-Beta 冲刺 (2/7)
  5. 团队GIT实战总结
  6. [转]让opencv输出人脸检测的得分(置信率)
  7. 用node研究axios前后端交互状态码规则
  8. Vue.js——60分钟browserify项目模板快速入门
  9. Java 输入/输出 反射
  10. STL 算法中函数对象和谓词