这里会显示出您选择的修订版和当前版本之间的差别。
python-files:ini [2010/12/20 04:54] |
python-files:ini [2010/12/20 04:54] (当前版本) |
||
---|---|---|---|
行 1: | 行 1: | ||
+ | ====== Python 处理 ini 格式文件 | ConfigParser的使用 ====== | ||
+ | |||
+ | ===== ini文件格式概述 ===== | ||
+ | |||
+ | ini 文件是文本文件,ini文件的数据格式一般为: | ||
+ | <code> | ||
+ | [Section1 Name] | ||
+ | KeyName1=value1 | ||
+ | KeyName2=value2 | ||
+ | ... | ||
+ | |||
+ | [Section2 Name] | ||
+ | KeyName1=value1 | ||
+ | KeyName2=value2 | ||
+ | </code> | ||
+ | ini 文件可以分为几个 Section,每个 Section 的名称用 [] 括起来,在一个 Section 中,可以有很多的 Key,每一个 Key 可以有一个值并占用一行,格式是 Key=value。 | ||
+ | |||
+ | |||
+ | ===== ConfigParser 类概述 ===== | ||
+ | ConfigParser 可以用来读取ini文件的内容,如果要更新的话要使用 SafeConfigParser. | ||
+ | ConfigParse 具有下面一些函数: | ||
+ | ==== 读取 ==== | ||
+ | * read(filename) 直接读取ini文件内容 | ||
+ | * readfp(fp) 可以读取一打开的文件 | ||
+ | * sections() 得到所有的section,并以列表的形式返回 | ||
+ | * options(sections) 得到某一个section的所有option | ||
+ | * get(section,option) 得到section中option的值,返回为string类型 | ||
+ | |||
+ | ==== 写入 ==== | ||
+ | 写入的话需要使用 SafeConfigParser, 因为这个类继承了ConfigParser的所有函数,\\ | ||
+ | 而且实现了下面的函数: \\ | ||
+ | set( section, option, value) 对section中的option进行设置 | ||
+ | |||
+ | ===== ConfigParser 使用例子 ===== | ||
+ | <code python> | ||
+ | from ConfigParser import SafeConfigParser | ||
+ | from StringIO import StringIO | ||
+ | |||
+ | f = StringIO() | ||
+ | scp = SafeConfigParser() | ||
+ | |||
+ | print '-'*20, ' following is write ini file part ', '-'*20 | ||
+ | sections = ['s1','s2'] | ||
+ | for s in sections: | ||
+ | scp.add_section(s) | ||
+ | scp.set(s,'option1','value1') | ||
+ | scp.set(s,'option2','value2') | ||
+ | |||
+ | scp.write(f) | ||
+ | print f.getvalue() | ||
+ | |||
+ | print '-'*20, ' following is read ini file part ', '-'*20 | ||
+ | f.seek(0) | ||
+ | scp2 = SafeConfigParser() | ||
+ | scp2.readfp(f) | ||
+ | sections = scp2.sections() | ||
+ | for s in sections: | ||
+ | options = scp2.options(s) | ||
+ | for option in options: | ||
+ | value = scp2.get(s,option) | ||
+ | print "section: %s, option: %s, value: %s" % (s,option,value) | ||
+ | </code> | ||
+ | 输出结果为: | ||
+ | <file> | ||
+ | -------------------- following is write ini file part -------------------- | ||
+ | [s2] | ||
+ | option2 = value2 | ||
+ | option1 = value1 | ||
+ | |||
+ | [s1] | ||
+ | option2 = value2 | ||
+ | option1 = value1 | ||
+ | |||
+ | |||
+ | -------------------- following is read ini file part -------------------- | ||
+ | section: s2, option: option2, value: value2 | ||
+ | section: s2, option: option1, value: value1 | ||
+ | section: s1, option: option2, value: value2 | ||
+ | section: s1, option: option1, value: value1 | ||
+ | |||
+ | </file> |