python3 configparser对配置文件读写

本文介绍了如何使用Python中的ConfigParser模块来读取、写入、修改、添加和删除配置文件中的section和option。通过具体代码示例展示了各项功能的实现方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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")

转载于:https://www.cnblogs.com/deadwood-2016/p/8116704.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值