<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
# '''
Python文件配置configParser使用
最新推荐文章于 2024-04-14 16:20:19 发布