python 配置文件读取模块 ConfigParser

前言:

任何语言都需要有一个读取配置文件的模块,python2.7 也不例外,用自带模块 ConfigParser 完成。(py3 用的是 configparser)

1.举个配置文件例子

文件名没有特殊要求,
eg,
value.conf

[people]
name = qing
age = 20
length = 175
[person]
name = quan
age = 25
height = 178
2.配置文件解析

配置文件以中括号 [] 来分组的
直接写一个代码来说明

import ConfigParser

cp = ConfigParser.ConfigParser()
cp.read("value.conf")		# 配置文件放当前目录,要不找不到,或者给配置文件的完整路径

people_name = cp.get('people', 'name')		# 结果为:qing
person_height = cp.get('person', 'height')	# 结果为:178
3.ConfigParser 模块方法说明

配置文件格式:[]包含的叫section,section下有 key = value 的键值对

(1). sections() 得到所有的section,并以列表的形式返回

sections = cp.sections()		# 结果为:['people', 'person']

(2). options(section) 得到该section的所有option

section = cp.sections()[0]
option = cp.options(section)	# 结果为:['name', 'age', 'length']

(3). items(section) 得到该section的所有键值对

section = cp.sections()[0]
item = cp.items(section)		# 结果为:[('name', 'qing'), ('age', '20'), ('length', '175')]

(4). get(section, option) 得到section中option的值,返回为string类型,getint(section, option) 返回的是 int 类型

people_name = cp.get('people', 'name')
people_age = cp.get('people', 'age')			# 结果为:20,为 int 类型

(5). add_section(), set() 方法补充配置信息

import ConfigParser

cp = ConfigParser.ConfigParser()
cp.read("value.conf")
cp.add_section('mine')			# 添加值为 mine 的section
cp.set('mine', 'name', 'quancheng')	# ming 下 name = quancheng
cp.write(open(config_file, 'a')) # a为追加

结果:

[people]
name = qing
age = 20
length = 175
[person]
name = quan
age = 25
height = 178
[mine]
name = quancheng
4. 其他方法可以参见 ConfigParser 类函数本身
发布了76 篇原创文章 · 获赞 46 · 访问量 11万+

猜你喜欢

转载自blog.csdn.net/qingquanyingyue/article/details/89973563