python读取配置文件(一)


这部分主要介绍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








  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值