自己寫的代碼
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]+'已經(jīng)存在'
? ? ? ? ? ? if student.cfg_has_option(add[0], add[1]):
? ? ? ? ? ? ? ? print add[0]+'中的'+add[1]+'已經(jīng)存在,現(xiàn)在將其刪除'
? ? ? ? ? ? ? ? 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]+'已經(jīng)存在,現(xiàn)在將其刪除'
? ? ? ? ? ? ? ? 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()
2017-01-07
O(∩_∩)O哈!