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

时间:2019-03-18
本文章向大家介绍python之读取配置文件模块configparser(三)高级使用---非标准配置文件解析,主要包括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)

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