篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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")