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 提供INI配置文件的操作 ConfigParser
- Python读写配置文件的实际操作步骤解析
- Python利用ConfigParser读取配置文件
- Python中利用ConfigParser操作配置文件
- Python 解析配置文件 (ConfigParser)模块
- Python(2.7.6) ConfigParser - 读写配置文件
- Python读写配置文件的实际操作步骤解析
- Python 之 ConfigParser : 配置文件读取
- 【Python】Python用ConfigParser管理配置文件
- [Python]ConfigParser解析配置文件
- [Python]ConfigParser解析配置文件
- Python利用ConfigParser读取配置文件
- python 中对配置文件(如.ini文件)进行读写等操作ConfigParser模块
- 【ConfigParser模块】Python处理配置文件
- Python 模块之 ConfigParser: 用 Python 解析配置文件
- Python读写配置文件的实际操作步骤解析
- Python利用ConfigParser读取配置文件
- python配置文件操作——configparser模块
- 【新手入门】Python下不喜欢使用ConfigParser去读取配置文件的Java developer
- python配置文件操作