码迷,mamicode.com
首页 > 编程语言 > 详细

python 之ConfigParser模块学习

时间:2017-02-21 19:29:06      阅读:178      评论:0      收藏:0      [点我收藏+]

标签:sub   学习   键值   cpu   efault   zha   dynamic   import   cti   

1.1 读取配置文件

-read(filename) 直接读取ini文件内容
-sections() 得到所有的section,并以列表的形式返回
-options(section) 得到该section的所有option
-items(section) 得到该section的所有键值对
-get(section,option) 得到section中option的值,返回为string类型
-getint(section,option) 得到section中option的值,返回为int类型
 

1.2 写入配置文件

-add_section(section) 添加一个新的section
-set( section, option, value) 对section中的option进行设置
  需要调用write将内容写入配置文件。

 

1.3 命令执行展示

config.ini内容如下:

[auth]
accesskey = HK6ICA0098BMC9421NMD
secretkey = BdbkPkgS0gJ586i9325i1rB10gZSIkW4i7uIsRYO

[api]
server = 192.168.8.56:8080
server = 192.168.8.56:8080
version = V1
default_regin = wuli11-777

[compute]
default_vpcid=989263d7-e897-4f0e-af6f-751a69def74c
default_msub_netid=589fdd7f-91a8-42a4-9fe9-add81448ef32
default_image_id=cef886fc-4b88-4f5d-980b-2df2b7e38f6b
default_cpu_count=1
default_mem_size=1
default_login_mode=passwd
default_password=Pass1115word
default_instance_name=name
default_pay_type=Pay_Dynamic


[shutdown]
default_instanceid=9d9f777e-9bbc-4ce8-91d2-638dc756aa3a

#导入ConfigParser模块

>>> import ConfigParser

#生存cf对象

>>> cf = ConfigParser.ConfigParser()
#读取配置文件
>>> cf.read("config.ini")
[‘config.ini‘]

#以列表方式返回所有的section
>>> sections = cf.sections()
>>> print ‘sections:‘, sections
sections: [‘auth‘, ‘api‘, ‘compute‘, ‘shutdown‘]

#获取指定section的所有option值
>>> options = cf.options("auth")
>>> print ‘options:‘,options
options: [‘accesskey‘, ‘secretkey‘]

#获取指定section所有的option的键值对
>>> valus = cf.items(‘auth‘)
>>> print valus
[(‘accesskey‘, ‘HK6ICA0098BMC9421NMD‘), (‘secretkey‘, ‘BdbkPkgS0gJ586i9325i1rB10gZSIkW4i7uIsRYO‘)]

#获取指定section,option的值,且值的类型为string
>>> valus1 = cf.get(‘auth‘,‘accesskey‘)
>>> print valus1
HK6ICA0098BMC9421NMD

#获取指定section,option的值,且值的类型为int
>>> valus2 = cf.getint(‘compute‘,‘default_cpu_count‘)
>>> print valus2
1

#更新指定section,option的值,如果option不存在,直接新增option以及对应的值

>>> cf.set(‘compute‘,‘default_cpu_count‘,‘2‘)
>>> cf.set(‘compute‘,‘name‘,‘luolijun‘)

#新增section test
>>> cf.add_section(‘test‘)

#给新增的section test增加option以及对应的值
>>> cf.set(‘test‘,‘test_name‘,‘zhangsan‘)

#将更改写入到配置文件中
>>> cf.write(open(‘config.ini‘,‘w‘))

python 之ConfigParser模块学习

标签:sub   学习   键值   cpu   efault   zha   dynamic   import   cti   

原文地址:http://www.cnblogs.com/wensiyang0916/p/6424555.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!