python 操作配置文件

#配置文件相关
import ConfigParser
def read_config(sec, opt, file):
    conf = ConfigParser.ConfigParser()
    conf.read(file)
    key_value = conf.get(sec,opt)
    print('read config input(%s,%s,%s) -> return value:%s' %(sec, opt, file,str(key_value)))
    return key_value
    
def write_config(value, file):
    num = 1
    conf = ConfigParser.ConfigParser()
    conf.read(file)
    for info in value:
        section = r'info%d'%num
        conf.add_section(section )
        conf.set(section , 'a', info[0])
        conf.set(section , 'b', info[1])
        conf.set(section , 'c', info[2])
        conf.set(section , 'd', info[3])
        num += 1
    conf.write(open(file, "w"))
    print('write config success')
if __name__ == '__main__':
    info = [[1,2,3,4],[5,6,7,8]]
    file = r'/home/py/test.ini'
    write_config(info, file)
    res = read_config('info1', 'a', file)
    ```
输出:
write config success
read config input(info1,a,/home/py/test.ini) -> return value:1

test.ini内容如下
[info1]
a = 1
b = 2
c = 3
d = 4

[info2]
a = 5
b = 6
c = 7
d = 8
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值