这部分主要介绍python 读写配置文件的例子以及相关代码的介绍
python读写配置文件在实际应用中还是非常广泛的,对这部分的初次了解纯属一种巧合,是通过做一个简单应用程序在遇到了一点问题,最后给出了配置文件的解决方法。(还是第一次了解)
python读写配置文件是用到ConfigParser模块,在这个模块中可以方便的读取写入等等。下面主要通过代码示例来介绍这个模块的应用。
#encoding: utf-8
import ConfigParser
#写配置文件 后缀名为.cfg 或者 .ini
config = ConfigParser.RawConfigParser()
print config
print type(config)
#两个部分sections 每个section下都会有options 和对应的values
try:
config.add_section('Section1')
config.set('Section1', 'an_int', '15')
config.set('Section1', 'a_bool', 'true')
config.set('Section1', 'a_float', '3.1415')
config.set('Section1', 'baz', 'fun')
config.set('Section1', 'bar', 'Python')
config.add_section('Section2')
config.set('Section2','ASC','101')
config.set('Section2','AGD','102')
config.set('Section2','AJX','103')
config.set('Section2','AGX','104')
config.set('Section2','AHB','105')
'''
sections options has_section has_option
'''
sections = config.sections() #返回section列表
print sections
for i in range(len(sections)):
temp = sections[i]
print temp
options = config.options(temp)
for j in range(len(options)):
key_value = '%s = %s' % (options[j],config.get(temp,options[j])) #取值,取option
print key_value
flag = config.has_section('Section1')
print flag
flag1 = config.has_option('Section2','ASC') #判断是否存在
print flag1
item = config.items('Section1') #返回键值列表
config.set('Section2','ASC','4242') #修改
except Exception,e:
print str(e)
# Writing our configuration file to 'example.cfg'
with open('example.cfg', 'wb') as configfile:
config.write(configfile)
config = ConfigParser.RawConfigParser()
config.read('example.cfg')
#读配置文件
a_float = config.getfloat('Section1', 'a_float')
an_int = config.getint('Section1', 'an_int')
print a_float + an_int
# This is because we are using a RawConfigParser().
if config.getboolean('Section1', 'a_bool'):
print config.get('Section1', 'a_bool')
运行结果:
<ConfigParser.RawConfigParser instance at 0x10335d0e0>
<type 'instance'>
['Section1', 'Section2']
Section1
an_int = 15
a_bool = true
a_float = 3.1415
baz = fun
bar = Python
Section2
asc = 101
agd = 102
ajx = 103
agx = 104
ahb = 105
True
参考资料:
https://docs.python.org/2/library/configparser.html
http://www.cnblogs.com/MikeZhang/archive/2011/11/19/2255169.html
http://developer.51cto.com/art/201003/189885.htm