python ConfigParser 参数化配置 学习笔记


python中ConfigParser 是用来读取配置文件的模块,可读写ini、cfg、conf等后缀的配置文件

rconf.ini
 
[auther]
;sections
name   = johnny
;options key = value 
gender = male
age    = 24
 
[information]
blogaddress = blog.csdn.net/z_johnny


read_write.py
 
#coding:utf-8
import ConfigParser

def read(rConfFileName):
    init = ConfigParser.ConfigParser()         # 初始化实例
    init.read("%s"%rConfFileName)              # 读取配置文件

    sections = init.sections()                 # 获取所有sections
    print "sections : ",sections               # 输出列表

    options = init.options("auther")           # 获取指定section 的options
    print "options : ",options                 # 输出列表,指定section里的所有key

    items = init.items("information")          # 获取指定section 的配置信息
    print "items : ",items

    information_blogaddress = init.get("information", "blogaddress") # 读取指定section中指定option 信息,type为str
    print "information_blogaddress : ",information_blogaddress

    auther_age = init.getint("auther", "age")  #获取的option为整型
    print "auther_age : ",auther_age

def write(wConfFileName):
    init = ConfigParser.ConfigParser()          # 初始化实例
    init.add_section('time')                    # 添加一个section
    init.set("time", "today", "sunday")         # 设置某个option 的值
    init.write(open("%s"%wConfFileName, "w"))   # 写入“w”,追加“a”

    init.add_section('times')                    # 添加一个要删除的section
    init.set("times", "tomorrowss", "mondays")   # 该项后面要删除
    init.remove_option('times','tomorrowss')     # 移除option,打开文件看一下,在把下面的注释(#)去掉
    #init.remove_section('times')                # 移除section 
    init.write(open("%s"%wConfFileName, "w"))    # 写入“w”,追加“a”

if __name__ == "__main__":
    read('rconf.ini')
    write('wconf.ini')                            # 自动创建wconf.ini


read输出:
sections :  ['auther', 'information']
options :  ['name', 'gender', 'age']
items :  [('blogaddress', 'blog.csdn.net/z_johnny')]
information_blogaddress :  blog.csdn.net/z_johnny
auther_age :  24

 
 

wirte输出文件wconf.ini
[time]
today = sunday

读取指定section中指定option 信息,获取到的内容type为str,如需转换成list,请看下面
ReadMe.ini
[reader]
qqqqqq = 15,26,30


#!/usr/bin/env python
#coding:utf-8
#2018/01/25 create by johnny

import ConfigParser

strChange = ConfigParser.ConfigParser()
strChange.read("C:\Users\Jim\Desktop\ReadMe.ini")
getstr = strChange.get("reader","qqqqqq")
strChangelist_eval = eval(getstr)
print strChangelist_eval,type(strChangelist_eval),strChangelist_eval[1],type(strChangelist_eval[1])




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值