python 之ConfigParser模块学习

本文介绍如何使用Python的ConfigParser模块来读取、修改和写入INI格式的配置文件。包括获取配置文件的section、option及键值对,更新配置项以及新增section等内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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'))

转载于:https://www.cnblogs.com/wensiyang0916/p/6424555.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值