python中的ConfigParser模块

1.简介

我们经常需要使用配置文件,例如.conf和.ini等类型,使用ConfigPaser模块可以对配置文件进行操作。

2.示例

现有配置文件test.ini,其内容如下:

[section_a]
a_key1 = str content
a_key2 = 10

[section_b]
b_key1 = b_value1
b_key2 = b_value2

2.1读取配置文件

1 # -*- coding=utf-8 -*-
2 import ConfigParser
3 import os
4 
5 # 生成config对象
6 os.chdir('C:\\Study\\python\\configparser')
7 cf = ConfigParser.ConfigParser()
8 # 读取配置文件
9 cf.read("test.ini")

2.2读取数据

1 # 读取所有节
2 sections = cf.sections()
3 print 'sections:', sections

结果如下:

------------------------

1 # 读取指定节的键
2 opts = cf.options('section_a')
3 print 'options:', opts

结果如下:

 

------------------------

1 # 读取指定节的所有键值对
2 kvs = cf.items('section_a')
3 print 'section_a:', kvs

结果如下:

 

------------------------

1 # 读取指定节和键的值
2 # 主要使用的有get()、getint()方法,前者为str类型,后者为int类型
3 kv1 = cf.get('section_a', 'a_key1')
4 print kv1, type(kv1)
5 kv2 = cf.getint('section_a', 'a_key2')
6 print kv2, type(kv2)

结果如下:

 

2.3写入数据

1 # 更新指定节和键的值
2 cf.set('section_b', 'b_key1', 'new_value1')

结果如下:

[section_a]
a_key1 = str content
a_key2 = 10

[section_b]
b_key1 = new_value1
b_key2 = b_value2

-------------------

1 # 对指定节,新增键
2 cf.set('section_b', 'b_key3')

结果如下:

[section_a]
a_key1 = str content
a_key2 = 10

[section_b]
b_key1 = new_value1
b_key2 = b_value2
b_key3 = None

-------------------

1 # 对指定节,新增键值对
2 cf.set("section_b", "b_new_key", "b_new_value")

结果如下:

[section_a]
a_key1 = str content
a_key2 = 10

[section_b]
b_key1 = new_value1
b_key2 = b_value2
b_key3 = None
b_new_key = b_new_value

-------------------

1 # 新增节
2 cf.add_section('section_c')

结果如下:

[section_a]
a_key1 = str content
a_key2 = 10

[section_b]
b_key1 = new_value1
b_key2 = b_value2
b_key3 = None
b_new_key = b_new_value

[section_c]

在所有写入完毕后,进行保存操作:

1 # 写入文件
2 cf.write(open('test.ini', 'w'))

!!!

 

转载于:https://www.cnblogs.com/jfl-xx/p/8023254.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值