ini配置文件打开模式 r,r+等

表格来源 http://www.cnblogs.com/dadong616/p/6824859.html

没有带+的都是只读或只写,带+则可读可写

Initconfig 操作
# -*- coding:utf-8 -*-
import ConfigParser#, os

class Initconfig:
    """read,write config ini file, default relative path :config.ini
        better explict use method close_f to close file
    """
    def __init__(self, filename = None):
        if not filename:
            filename = 'config.ini'
        self.filename = filename
        self.cfg = ConfigParser.ConfigParser()
        
    def get_value(self, Section, Key, Default = ""):
        self.cfg.read(self.filename)
        try:
            value = self.cfg.get(Section, Key)
        except:
            value = Default
        return value

    def set_value(self, Section, Key, Value):
        with open(self.filename, 'w+') as fp:
            if not self.cfg.has_section(Section):
                self.cfg.add_section(Section)  
            self.cfg.set(Section, Key, Value)
            self.cfg.write(fp)

这样的类,在get某个值时才io,每次读取或写入都得io,因此适合只少量配置变量

读比较简单:

  self.cfg.read(self.filename),直接读取文件;若文件不存在,并不会报错,只是读取的内容为空:

xxx = Initconfig('xxx.ini')
xxx.cfg.sections()
Out[99]: []

写,使用w+,会覆盖掉原来同样的变量;

使用a+ ,在后面追加,如同日志文本一样

而追加写之后,有多个同块同名变量,只会读取到最后那个

原文地址:https://www.cnblogs.com/willowj/p/7171784.html