读写配置文件ConfigParser

xiaoxiao2021-02-28  79

ConfigParser读写配置文件 #ini配置文件格式 """ 节:【session】 参数(键=值):name=value 例: 节:【port】 参数: port1:8081 port2:8082 """ import ConfigParser #创建configparser对象 cfg=ConfigParser.ConfigParser() #将文件load进入 cfg.read('/Users/mac/Desktop/text.txt') print cfg.sections() #文件的遍历 for se in cfg.sections(): #打印出所有的section print se #打印出section中的key,value的值 print cfg.items(se) #修改条目 cfg.set('userinfo','pwd','1234567') #修改条userinfo section中的pwd的值 cfg.sections('userinfo','email','abc@163.com') #增加section中的email的值 cfg.remove_section('login') #删除整个section cfg.remove_option('userinfo','email') #删除userinfo section中的email option的值 #以下类实现的功能 import os import os.path import ConfigParser """ 1.dump ini 2.del section 3.del item 4.modify item 5.add section 6.save modify text文件的内容: [userinfo] name=zhangsan pwd=abc [study] python_base=15 python_junior=20 linux_base=15 """ class student_info(object): def __init__(self,recordfile): self.logfile=recordfile self.cfg=ConfigParser.ConfigParser() #dump ini def cfg_load(self): self.cfg.read(self.logfile) #del section def del_section(self,section): self.cfg.remove_section(section) #del option def del_item(self,section,key): self.cfg.remove_option(section,key) #add item def add_item(self,section,key,value): self.cfg.set(section,key,value) #add_section def add_section(self,section): self.cfg.set(section) #save文件 def save(self,logfile): fp=open(logfile,'w') self.cfg.write(fp) fp.close() #遍历section和item def dump_list(self): se_list=self,cfg.sections() print "++++++++++++++++++++++++++++++++++++++" for se in se_list: print se print self.cfg.items(se) print "++++++++++++++++++++++++++++++++++++++" if __name__=='__main__': #传入的参数是看init里有几个参数 info=student_info('/Users/mac/Desktop/text.txt') info.cfg_load() info.add_section('login') info.add_item('login','date','20170708') info.del_item('login','date') info.del_section('login') info.dump_list() info.save('/Users/mac/Desktop/text.txt')
转载请注明原文地址: https://www.6miu.com/read-20526.html

最新回复(0)