读写配置文件ConfigParser

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')
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值