您的位置:首页 > 其它

读写配置文件ConfigParser

2017-05-05 10:54 357 查看
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')
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: