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
1读取配置文件
import ConfigParser
import os
# 生成config对象
os.chdir('C:\\Study\\python\\configparser')
cf = ConfigParser.ConfigParser()
# 读取配置文件
cf.read("test.ini")
2读取数据
# 读取所有节
sections = cf.sections()
print 'sections:', sections
结果如下:
# 读取指定节的键
opts = cf.options('section_a')
print('options:', opts)
结果如下:
# 读取指定节的所有键值对
kvs = cf.items('section_a')
print ('section_a:', kvs)
结果如下:
# 读取指定节和键的值
# 主要使用的有get()、getint()方法,前者为str类型,后者为int类型
kv1 = cf.get('section_a', 'a_key1')
print kv1, type(kv1)
kv2 = cf.getint('section_a', 'a_key2')
print kv2, type(kv2)
结果如下:
3写入数据
更新指定节和键的值
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
对指定节,新增键
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
对指定节,新增键值对
cf.set("section_b", "b_new_key", "b_new_value")
结果如下:
'''
学习中遇到问题没人解答?小编创建了一个Python学习交流QQ群:857662006
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
[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
新增节
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]
在所有写入完毕后,进行保存操作:
# 写入文件
cf.write(open('test.ini', 'w'))