python之读取配置文件模块configparser(三)高级使用---非标准配置文件解析

非标准配置文件也是经常使用的,如何使用configparser来解析?

这要从configparser本身解析结构来说,configparser包含section和option,非标准配置文件只有option,那么可以人为先加上一个section最后再去掉section

思路是这样,那么就可以操作了,我们使用config.ini文件如下:

globalmd5 = functest
port = 9900
address = http://sdv.functest.com

 

具体转换和增删改查操作参看如下代码:

import configparser
import os

filepath = os.path.join(os.getcwd(),'config.ini')
print(filepath)
sectionname = 'temp'

#把普通配置文件转换为有section的文件
def trans2ini(path,sectionname):
    with open(path,'r') as f:
        f_temp = f.read()
    with open(path,'w') as f:
        f.write('[' + sectionname + ']\n' + f_temp)

#转换为不带section的配置文件
def trans2normal(path):
    with open(path,'r') as f:
        f.readline()
        f_temp = f.read()
    with open(path,'w') as f:
        f.write(f_temp)

#查询操作
def select(filepath,configparser):
    configparser.read(filepath)
    for i in configparser.sections():
        print('[' + i + ']')
        for k,v in configparser.items(i):
            print(k,'=',v)

#修改操作
def update(fielpath,configparser,section,option,value):
    configparser.read(filepath)
    configparser.set(section,option,value)
    with open(filepath,'w+') as f:
        configparser.write(f)

#删除option操作
def delete_option(filepath,configparser,section,option):
    configparser.read(filepath)
    configparser.remove_option(section,option)
    with open(filepath,'w+') as f:
        configparser.write(f)

#删除section操作
def delete_section(filepath,configparser,section):
    configparser.read(filepath)
    configparser.remove_option(section)
    with open(filepath,'w+') as f:
        configparser.write(f)

#增加操作
def insert(filepath,configparser,section,options,values):
    configparser.read(filepath)
    if section not in configparser.sections():
        configparser.add_section(section)
    for i in range(len(options)):
        configparser.set(section,options[i],values[i])
    with open(filepath,'w+') as f:
        configparser.write(f)

#转换为带section的ini文件
trans2ini(filepath,sectionname)
cp = configparser.ConfigParser()
print('查询原始文件:')
select(filepath,cp)

print('修改port为8809:')
update(filepath,cp,sectionname,'port','8809')
select(filepath,cp)

print('删除port:')
delete_option(filepath,cp,sectionname,'port')
select(filepath,cp)

print('增加port:')
insert(filepath,cp,sectionname,['port'],['8001'])
select(filepath,cp)

#操作完成后删除section
trans2normal(filepath)

 

以上仅作为参考,有更好思路请留言交流

 

转载于:https://www.cnblogs.com/watertaro/p/10554450.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值