python3 configparser对配置文件读写

import configparser

#read data from conf file
cf=configparser.ConfigParser()
cf.read("biosver.cfg")

#返回所有的section
s=cf.sections()
print(s)

#返回information section下面的option
o1=cf.options('Information')
print(o1)

#返回information section下面的option的具体的内容
v1=cf.items("Information")
print(v1)

#得到指定项的值
name=cf.get('Information','name')
print(name)

#添加section

if cf.has_section("del"):
    print("del section exists")
else:
cf.add_section('del')
cf.set("del","age","12")
cf.write(open("biosver.cfg","w"))

#删除option
if cf.has_option("del",'age'):
print("del->age exists")
cf.remove_option("del","age")
cf.write(open("biosver.cfg","w"))
print("delete del->age")
else:
print("del -> age don't exist")

#删除section
if cf.has_section("del1"):
cf.remove_section("del1")
cf.write(open("biosver.cfg","w"))
else:
print("del1 don't exists")

#modify a value
cf.set("section","option","value")
posted @ 2017-12-26 10:26  deadwood_2016  阅读(234)  评论(0编辑  收藏  举报