此模块用于读取基于windows环境下的.ini格式配置文件。
ini格式如下:
[section]
name1=value1
name2=value2
[section2]
name3:value3
name4:value4
section是自己定义的名字,下面是它的变量赋值
1、创建一个实例:
from configparser import ConfigParser
cf=ConfigParser([defaults[,dict_type]])
可选参数defaults是一个字典,如果想使用这个参数,示例:
defaults={'name':'rose','phone':155643}
cf=ConfigParser(defaults)
2、读取配置文件:
cf.read(filenames)
filenames可以是文件名,也可以是文件名列表
3、获取配置文件信息:
cf.get(section,option) section就是.ini文件中的[section],option是=号左边的名字。
cf.get(section2,name3)
返回value3
cf.options(section) 返回section中所有选项的列表:
[name1,name2,'name','phone']
其中‘name’,'phone'是defaults中的键值,如果没有defaults,只返回[name1,name2]
cf.sections() 返回所有得section名列表
4、修改配置文件中的数据:
cf.remove_section(section) 删除section段
cf.remove_option(section,option) 删除section中的option
cf.set(section,option,value) 向section中加入option及赋予的值value。
5、将数据写入file:
cf.write(file) file是已经打开的类文件对象