您的位置:首页 > 编程语言 > Python开发

python操作配置文件configparser 增删改查

2017-02-02 12:03 519 查看
```
来源于慕课网。按照视频讲解进行练习,记录联系过程。
```
import os
import os.path
import configparser
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):
se_list = self.cfg.sections()
print('================= %s'% type(se_list))
for se in se_list:
print(se)
print(type(se))
print(self.cfg.items(se))
print('=================')
def delete_item(self,section,key):
self.cfg.remove_option(section,key)
def delete_section(self,section):
self.cfg.remove_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('immoc.txt')
info.cfg_load()
info.cfg_dump()
info.set_item('userinfo','pwd','abc')
info.cfg_dump()
info.add_section('login')
info.set_item('login','2015-0511','20')
info.cfg_dump()
info.save()

最基本的增删该查。

1.如果文件为空。会出异常。找不到item。

    使用只写打开文件不存在打不开的情况(除非文件描述符占用太多)

2.把configparser的初始化传给self.cfg。方便操作。可以在一个item下增加也可以新增一个item。

3.python的第三方库非常强大。写代码很快。

4.对配置文件的操作可以复用。以配置文件为根。当做配置文件。可以动态添加。动态修改。比直接操作txt文件强很多。(也可以用正则操作xml效果类似)

   过一段时间把用shell写的配置文件解析搬移过来。

5.python中configparser对文件的操作最开始都是在内存中。并不是真正的对这个文件。最后close之后会把内存中的数据存放到文件中。才是真正操作文件了。

5.目前基本的python语法ok了。需要做项目巩固一下。有哪些比较好的项目呢。最好是能够真用上的。感觉像什么图书管理系统就算了吧。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python configparser