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

 

ConfigParser 是Python自带的模块, 用来读写配置文件, 用法及其简单。 直接上代码,不解释,不多说。

配置文件的格式是: []包含的叫section,    section 下有option=value这样的键值

配置文件   test.conf    

[section1]
name = tank
age = 28

[section2]
ip = 192.168.1.1
port = 8080

Python代码
# -* - coding: UTF-8 -* -  
import ConfigParser

conf = ConfigParser.ConfigParser()
conf.read("c:\\test.conf")

# 获取指定的section, 指定的option的值
name = conf.get("section1", "name")
print(name)
age = conf.get("section1", "age")
print age

#获取所有的section
sections = conf.sections()
print sections

###########################################################
#写配置文件

# 更新指定section, option的值
conf.set("section2", "port", "8081")

# 写入指定section, 增加新option的值
conf.set("section2", "IEPort", "80")

# 添加新的 section
conf.add_section("new_section")
conf.set("new_section", "new_option", "http://www.cnblogs.com/tankxiao")

# 写回配置文件
conf.write(open("c:\\test.conf","w"))

 


 

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之后会把内存中的数据存放到文件中。才是真正操作文件了。

 

你可能感兴趣的:(python操作配置文件configparser 增删改查)