自己写的代码

来源:4-1 文件练习

慕粉1012007540

2017-01-07 23:53

import ConfigParser

import os


class student_info(object):

    def __init__(self,recordfile):

        self.logfile=recordfile

        self.cfg=ConfigParser.ConfigParser()

    def cfg_load(self):

        self.cfg.read(self.logfile)

    def cfg_dump(self):

        for sec in self.cfg.sections():

            print sec

            print self.cfg.items(sec)

    def cfg_del_section(self,section):

        self.cfg.remove_section(section)

    def cfg_add_section(self,section):

        self.cfg.add_section(section)

    def cfg_add_item(self,section,option,value):

        self.cfg.set(section,option,value)

    def cfg_del_item(self,section,option):

        self.cfg.remove_option(section,option)

    def cfg_has_section(self,section):

        return self.cfg.has_section(section)

    def cfg_has_option(self,section,option):

        return self.cfg.has_option(section, option)

    

    def save(self):

        fg=open(self.logfile,'w')

        self.cfg.write(fg)

        fg.close()

if __name__=='__main__':

    

    filepath='D:\python\imooc.txt'        

    student=student_info(filepath)

    student.cfg_load()

    student.cfg_dump()

    

    add_list=[('grade','math','99'),('grade','Chinese','100'),('userinfo','email','123@qq.com')]

    for add in add_list:

        if student.cfg_has_section(add[0]):

            print add[0]+'已经存在'

            if student.cfg_has_option(add[0], add[1]):

                print add[0]+'中的'+add[1]+'已经存在,现在将其删除'

                student.cfg_del_item(add[0], add[1])

            else:

                student.cfg_add_item(add[0], add[1], add[2]) 

                print '已在'+add[0]+'中'+'添加'+add[1]

        else:

            student.cfg_add_section(add[0])

            if student.cfg_has_option(add[0], add[1]):

                print add[0]+'中的'+add[1]+'已经存在,现在将其删除'

                student.cfg_del_item(add[0], add[1])

            else:

                student.cfg_add_item(add[0], add[1], add[2])

                print '已在'+add[0]+'中'+'添加'+add[1]

    

    student.save()

    student.cfg_dump()



写回答 关注

1回答

  • 慕粉1012007540
    2017-01-07 23:53:46

    O(∩_∩)O哈!

    兰陵萧萧笙

    厉害了

    2017-10-23 10:14:14

    共 1 条回复 >

Python文件处理

Python文件操作指南,掌握os模块对文件和目录的处理

88451 学习 · 112 问题

查看课程

相似问题