Python文件配置configParser使用

<pre name="code" class="python"># -*- coding:gb2312 -*-
import ConfigParser

class student_info(object):
    '''
1.dump ini
2.del section
3.del item
4.modify item
5.add section
6.save modify
'''
    def __init__(self, recordfile):
        # 文件名字
        self.logfile = recordfile
        self.cfg = ConfigParser.ConfigParser()

    # 将文件load到cfg中
    def cfg_load(self):
        self.cfg.read(self.logfile)

    # 将写入内存中的内容显示出来(这些操作并不是在我们磁盘文件中的修改)
    def cfg_dump(self):
        se_list = self.cfg.sections()
        print "===================>"
        for se in se_list:
            print se    # se相当于一个字典
            print self.cfg.items(se)
        print "<=================="

    # 删除条目
    def delete_item(self, section, key):
        self.cfg.remove_option(section, key)

    # 删除section(课程)
    def delete_section(self, section):
        self.cfg.remove_section(section)

    # 添加一个section
    def add_section(self, section):
        self.cfg.add_section(section)

    # 添加和修改条目
    def set_item(self, section, key, value):
        self.cfg.set(section, key, value)

    def save(self):
        fp = open(self.logfile, 'w')
        self.cfg.write(fp)
        fp.close()

if __name__ == '__main__':
    info = student_info('liuyc.txt')
    info.cfg_load()
    info.cfg_dump()
    info.add_section('yuwen')   # 第二次需要注释掉
    info.set_item('yuwen', 'liuyc', '88')
    info.set_item('yuwen', 'xiongda', '20')
    info.set_item('yuwen', 'xionger', [1,2,3,4,5])
    info.cfg_dump()
    info.save()

# '''
# ini配置文件格式:
# 节:[session]
# 参数(键=值) name=value
# '''




                
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值