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

本文介绍了一个用于管理Python配置文件的类Initconfig,该类支持读取和写入INI格式的配置文件。通过实例演示了如何使用这个类进行配置项的获取和设置。

 

表格来源 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值