python中ConfigParser 是用来读取配置文件的模块,可读写ini、cfg、conf等后缀的配置文件
rconf.ini
[auther] ;sections name = johnny ;options key = value gender = male age = 24 [information] blogaddress = blog.csdn.net/z_johnnyread_write.py
#coding:utf-8 # ======================================================================= # FuncName: read_write.py # Desc: read and write file # Date: 2016-03-06 17:00 # Author: johnny # ======================================================================= import ConfigParser def read(rConfFileName): init = ConfigParser.ConfigParser() # 初始化实例 init.read("%s"%rConfFileName) # 读取配置文件 sections = init.sections() # 获取所有sections print "sections : ",sections # 输出列表 options = init.options("auther") # 获取指定section 的options print "options : ",options # 输出列表,指定section里的所有key items = init.items("information") # 获取指定section 的配置信息 print "items : ",items information_blogaddress = init.get("information", "blogaddress") # 读取指定section中指定option 信息 print "information_blogaddress : ",information_blogaddress auther_age = init.getint("auther", "age") #获取的option为整型 print "auther_age : ",auther_age def write(wConfFileName): init = ConfigParser.ConfigParser() # 初始化实例 init.add_section('time') # 添加一个section init.set("time", "today", "sunday") # 设置某个option 的值 init.write(open("%s"%wConfFileName, "w")) # 写入“w”,追加“a” init.add_section('times') # 添加一个要删除的section init.set("times", "tomorrowss", "mondays") # 该项后面要删除 init.remove_option('times','tomorrowss') # 移除option,打开文件看一下,在把下面的注释(#)去掉 #init.remove_section('times') # 移除section init.write(open("%s"%wConfFileName, "w")) # 写入“w”,追加“a” if __name__ == "__main__": read('rconf.ini') write('wconf.ini') # 自动创建wconf.ini
read输出:
sections : ['auther', 'information'] options : ['name', 'gender', 'age'] items : [('blogaddress', 'blog.csdn.net/z_johnny')] information_blogaddress : blog.csdn.net/z_johnny auther_age : 24wirte输出文件wconf.ini
[time] today = sunday