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