码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2017-07-14 18:52:37      阅读:189      评论:0      收藏:0      [点我收藏+]

标签:文本   写入   elf   内容   path   image   表格   style   relative   

 

技术分享

表格来源 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+ ,在后面追加,如同日志文本一样

 

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

 

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

标签:文本   写入   elf   内容   path   image   表格   style   relative   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!