Python的ConfigParser Module 中定义了3个类对INI文件进行操作。分别是RawConfigParser、ConfigParser、SafeConfigParser。 RawCnfigParser是最基础的INI文件读取类,ConfigParser、SafeConfigParser支持对%(value)s变量的 解析。

一、类和方法

1、RawConfigParser实例方法

**defaults() :**返回全部示例中所以defaults。

**sections() :**返回有效的section列表,DEFAULT不包含在列表中。

**add_section(section) :**为实例添加一个section,如果给定的section名已经存在,将抛出DuplicateSectionError异常。

**has_section(section) :**判断给定的section名在配置文件中是否存在,DEFAULT section不包括。

**options(section) :**返回给定的section下的所有可用option的列表。

**has_option(section, option) :**如果section存在,并包含给定的option,返回true,放在返回false, 1.6版本新增。

**read(filenames) :**尝试解析文件列表,如果解析成功返回文件列表。如果filenames是string或Unicode string,将会按单个文件来解析。如果在filenames中的文件不能打开,该文件将被忽略。这样设计的目的是,让你能指定本地有可能是配置文件的 列表(例如,当前文件夹,用户的根目录,及一些全系统目录),所以在列表中存在的配置文件都会被读取。如果文件都不存在,那么ConfigParser实 例会包含空数据集。一个需要从配置文件读取初始化数据的应用程序,应该使用readfp()方法来加载所需要的文件,之后可以使用read()方法来获取 任何可能的文件:2.4版本之后,返回成功解析的文件列表。

**readfp(fp[, filename]) :**从文件或fp(值使用该对象的readline()方法)中的似文件类读取并解析配置数据,如果filename被省略,fp有一个name属性,该属性用于获取filename 。

**get(section, option) :**获取section下option的值。

**getint(section, option) :**强制指定section下的option的值,作为Int类型返回的方便方法。

**getfloat(section, option) :**强制section下的option值,作为float类型返回的方法方法。

**getboolean(section, option) :**强制section下的option值,作为布尔类型返回的方法方法。注意可接受的option的true值有“1”,“yes”,“true”及 “on”,可接受的false值有“0”,“no”,“false”,“off”。字符串值不检测大小写,其他值会抛出ValueError异常。

**itmes(section) :**返回给定section下的所以option的(name, value)对列表。

**set(section, option, value) :**如果给定的setion存在,为option设定给定的值;否则抛出NoSectionError异常。当可能使用RawConfigParser(或者 ConfigParser的参数raw为true)来在内部存储非字符串值,所以功能(包括填补和输出到文件)只能使用字符串值来归档。1.6版本新增。

**write(fileobject) :**将配置表示写入指定文件类,该表示以后可以通过调用read()来解析,1.6版本新增。

**remove_option(section, option) :**从指定section中删除指定option,如果section不存在,抛出NoSectionError异常;如果option存在,则删除,并返回True;否则返回false。1.6版本新增。

**remove_section(section) :**从配置文件中删除指定的section,如果section确实存在,返回true,否则返回false。

**optionxform(option) :**将输入文件中,或客户端代码传递的option名转化成内部结构使用的形式。默认实现返回option的小写形式;子类可能重写该方法或客户端代码可能将该方法作为实例的属性,以此来影响它的行为。将此用于str(),例如,会使option名称大小写敏感。

2、ConfigParser对象方法

ConfigParser类扩展了RawConfigParser的一些接口方法,添加了一些可选参数。

**get(section, option [, raw[, vars]]) :**获取给定section下的option的值,所以“%”占位符在返回值中被填补,基于构造时传递的默认值,就像option,vars也被提供,除非raw参数为true。

**items(section, [, raw[, vars]]) :**返回给定section下的所以option的(name, value)对列表。可选参数同get方法,2.3版本新增。

3、SafeConfigParser对象中的方法

SafeConfigParser类实现了ConfigParser相同的接口,新增如下方法:

**set(section, option, value) :**如果给定的section存在,给option赋值;否则抛出NoSectionError异常。Value值必须是字符串(str或unicode);如果不是,抛出TypeError异常,2.4版本新增。

二、使用示例

dbconf.ini文件

1[baseconf]
2host=127.0.0.1
3port=3306
4user=root
5password=root
6db_name=evaluting_sys
7[concurrent]
8processor=20

读写代码:

 1import sys,os
 2import ConfigParser
 3def test(config_file_path):
 4    cf = ConfigParser.ConfigParser()
 5    cf.read(config_file_path)
 6    s = cf.sections()
 7    print 'section:', s
 8    o = cf.options("baseconf")
 9    print 'options:', o
10    v = cf.items("baseconf")
11    print 'db:', v
12    db_host = cf.get("baseconf", "host")
13    db_port = cf.getint("baseconf", "port")
14    db_user = cf.get("baseconf", "user")
15    db_pwd = cf.get("baseconf", "password")
16    print db_host, db_port, db_user, db_pwd
17    cf.set("baseconf", "db_pass", "123456")
18    cf.write(open("config_file_path", "w"))
19if __name__ == "__main__":
20    test("../conf/db_config.ini")

也可以按如下用法处理muti_site.ini

1[site]
2url = https://blog.361way.com/
3username = 361way
4password = nothing
5[site2]
6url = http://www.91it.org/
7username = 91it
8password = org

读取代码如下:

1from ConfigParser import SafeConfigParser
2parser = SafeConfigParser()
3parser.read('multisection.ini')
4for section_name in parser.sections():
5    print 'Section:', section_name
6    print '  Options:', parser.options(section_name)
7    for name, value in parser.items(section_name):
8        print '  %s = %s' % (name, value)

在对ini文件里的不存在的key进行取值时,如取username1,由于不存在会报错,针对该问题,可以使用下面的一个类进行处理:

 1import sys,os,time
 2import ConfigParser
 3class Config:
 4    def __init__(self, path):
 5        self.path = path
 6        self.cf = ConfigParser.ConfigParser()
 7        self.cf.read(self.path)
 8    def get(self, field, key):
 9        result = ""
10        try:
11            result = self.cf.get(field, key)
12        except:
13            result = ""
14        return result
15    def set(self, filed, key, value):
16        try:
17            self.cf.set(field, key, value)
18            cf.write(open(self.path,'w'))
19        except:
20            return False
21        return True
22def read_config(config_file_path, field, key):
23    cf = ConfigParser.ConfigParser()
24    try:
25        cf.read(config_file_path)
26        result = cf.get(field, key)
27    except:
28        sys.exit(1)
29    return result
30def write_config(config_file_path, field, key, value):
31    cf = ConfigParser.ConfigParser()
32    try:
33        cf.read(config_file_path)
34        cf.set(field, key, value)
35        cf.write(open(config_file_path,'w'))
36    except:
37        sys.exit(1)
38    return True
39if __name__ == "__main__":
40   if len(sys.argv) < 4:
41      sys.exit(1)
42   config_file_path = sys.argv[1]
43   field = sys.argv[2]
44   key = sys.argv[3]
45   if len(sys.argv) == 4:
46      print read_config(config_file_path, field, key)
47   else:
48      value = sys.argv[4]   #值从0-4,第5个值的下标为4
49      write_config(config_file_path, field, key, value)