python--ConfigParser

本章主要总结python读取配置文件的用法。

【配置文件】

[section]
option1 = value1
option2 = value2
option3 = value3
#值可以通过“%(option_name)s”获取对应值 option4
= %(option3)s is %(option2)s! [section2] option1 = value1 option2 = value2
#值可以换行 option5: this value continues
in the next line

【写入文件】

import ConfigParser

conf = ConfigParser.RawConfigParser()

#添加section
conf.add_section("section")
#在section下添加内容
conf.set("section", "option1", "value1")
conf.set("section", "option2", "value2")
conf.set("section", "option3", "value3")
conf.set("section", "option4", "%(option3)s is %(option2)s!")

#将信息写入文件中
with open('exam1.cfg','wb') as configfile:
    conf.write(configfile)

【读取文件】

import ConfigParser

#引用RawConfigParser类 conf
= ConfigParser.RawConfigParser() #读取文件 conf.read("exam1.cfg") #返回sections列表 print conf.sections() #是否存在“section” print conf.has_section("section") #返回“section”下的option列表 print conf.options("section")

###
RawConfigParser类获取值:直接输出
#print conf.get("section", "option4") ---输出:%(option3)s is %(option2)s!
#获取“section2”中,“option5”的值
print conf.get("section2", "option5")
#返回(option,value)键对列表
print conf.items("section2")

输出值:

['section', 'section2']
True
['option1', 'option2', 'option3', 'option4']
this value continues
in the next line
[('option1', 'value1'), ('option2', 'value2'), ('option5', 'this value continues
in the next line')]

【篡改文件】

import ConfigParser

#引用ConfigParser类
config = ConfigParser.ConfigParser()
config.read('exam1.cfg')
#第三个参数控制是否读取原生值。
#如果是0,则取运算后的值;
#如果是1,则取原生值;
###ConfigParser类输出--参数判断输出内容 print config.get("section", "option4",0) print config.get("section", "option4",1) #get()方法的第四个参数可修改value; #第四个参数要求字典格式; #当第四个参数存在时,篡改value的优先级为最高; print config.get("section", "option4", 0, {'option3':'changevalue3','option2':'changevalue2'})

输出:
value3 is value2!
%(option3)s is %(option2)s!
changevalue3 is changevalue2!
import ConfigParser

#引用SafeConfigParser类;
#当配置文件的option没有获取到值时,会取值下面配置的值
config = ConfigParser.SafeConfigParser({'option2':'life','option3':'safechangevuale3'})
config.read('exam1.cfg')

###SafeConfigParser类输出--输出运算后的值
print config.get("section", "option4") config.remove_option("section", "option2") config.remove_option("section", "option3") print config.get("section", "option4")

输出:

value3 is value2!
safechangevuale3 is life!

以上更多的是举例说明,具体的方法可在官方文档中查看(地址:https://docs.python.org/2.7/library/configparser.html) 

原文地址:https://www.cnblogs.com/susan-su/p/8746940.html