configparser

来源:互联网 发布:淘宝客服是干嘛的 编辑:程序博客网 时间:2024/05/16 19:06
利用configparser模块可以更方便的写配置文件
import configparser as cp#配置文件写入config = cp.ConfigParser()#创建对象config['DEFAULT']={'class':'attrib'}config['CHOOSE1']={'class':'attrib'}config['CHOOSE2']={'class':'attrib'}#直接用字典将属性写入with open(file,'w') as configFile:    configFile.write(config)    #写入文件自动调整格式#配置文件读取config = cp.ConfigParser()#创建配置文件对象config.read(filename)#加载指定配置文件config.sections()#打印配置文件下的主分支,不打印默认config['DEFAULT']['class']#层级字典查找属性值,第一层返回的是字典列表,后面是层级字典config.remove_section(sectionname)#移除一个分支config.remove_option(optionname)#移除分支下一个参数config.get(seciotn,option)#获取指定配置,和字典调用相同config.getboolean()config.getfloat()config.getint()#同get,底层自动转型config.has_option('option')config.has_section('section')#判断有无指定分支或选项config.add_section('section')#添加分支,分支下选项option用字典直接赋值config.write(file)#写入指定文件,输入file为文件对象

原创粉丝点击