[Python]配置文件的增删改查-ConfigParser

>API

configparser(3.x)和ConfigParser(2.x)是Python中原生的用于解析配置文件的模块。其API文档地址>点此<

>配置文件语法结构

配置文件需要是一个标准text文件,后缀名无所谓。其主要结构为Section模式,采用键值对的方式存储配置值:

[Section1]
Key1 = Value1
Key2 = Multiple_lines1
    Multiple_line2 # 注释需要单起一行
# This is a comment
; and this is a comment too.
Key3 = 10086
Key4 = False

键值对Key=Value在该结构中,每一个Key被称为Option,可由Options('Section_Name')来获取某个Section下的所有Key的值(不是值Key=Value中的Value,而是每个Key的'名');Value的值可以由多行组成,但是需要缩进;其中,注释由#;单独换行引出。

>ConfigParser常见操作:查

在读取一个配置文件实例时,先要把该配置文件利用ConfigParser().read('config_path')方法加载进来。以SysConfig.ini作为配置文件、Python2.7版本为例:

import ConfigParser

cp = ConfigParser.ConfigParser()
cp.read('%ConfigDir%/SysConfig.ini')

注意给出配置文件的相对地址%ConfigDir%,不再赘述。同时,在Python3.x它也可以直接读一个字典,如:

dict = {
    'Sec1': {
        'Key1': 'Value1',
        'Key2': 'Value2'
    },
    'Sec2': {
        'Key1': 'Value1',
        'Key2': 'Value2'
    }
}
cp.read_dict(dict)

查询时,通过Section名和Key名,利用ConfigParser().get()方法查询:

print cp.get('Section1', 'Key1')

遍历时,利用options()方法获取所有Key名,并利用get()方法读取:

for i in cp.options('Section1'):
    print i, '=', cp.get('Section1', i)

同理,要想获取所有的Section的名,可以用sections()方法获取,不再赘述。

要想同时获取某个Section下的所有键值对,可以利用items方法获取(但要注意该方法获取的所有字符串,都会变成小写和utf-8编码,即中文会被encode),返回为一个list包含若干个键值对元组:

for i in cp.items('Section1'):
    print i  # 小写&utf-8编码
    print i[0], '=', i[1]  # 正常显示

最后,get()方法获得的所有Value都是String,要想获得integer,需要将get()方法改为getint()方法——同样,还有getboolean()和getfloat()方法,其中,boolean值为True/False。

此外,还有has_section('Section')、has_option('Section', 'Option')等方法用于判断是否包含某章节/条目。

>ConfigParser常见操作:增/改

增加主要使用两个函数:set('Section', 'Key', 'newValue')和add_section('newSection')方法。

增加一个Section方法:

cp.add_section('Section2')

增加/修改一个新的键值对到新的Section中:

cp.set('Section2', 'newKey1', 'newValue1')

要想把增/改完毕的Config写入配置文件进行本地保存,需要调用write()函数:

cp.write(open('%ConfigDir%/SysConfig.ini', 'w'))

如果没有进行write()写入硬盘,就只会在内存中保存,程序结束运行或内存被回收后将会丢失修改后的操作。

>ConfigParser常见操作:删

删主要利用两个函数:remove_section('Section')和remove_option('Section', 'Key'):

cp.remove_option('Section2', 'newKey1')
cp.remove_section('Section2')

>[DEFAULT]

 章节名为[DEFAULT]的为默认章节,可以直接通过default()方法读出来。该Section无法被移除。

 

猜你喜欢

转载自blog.csdn.net/Shenpibaipao/article/details/81081638