Python configparser修改配置文件

公司的产品部署在Linux服务器上,安装好后需要在配置文件中设置许多性能参数以达到最佳performance. Python中的configparser可以很方便的修改config文件,将调整好的参数写在一个config文件中,每次新安装产品后解析config文件,将对应的参数写入系统的config文件。
以下是示意:
模版文件 test1.conf内容如下:

[s1]
size=800
len=400


[s2]
user=root
passwd=root




需要将test2.conf中的参数值改为test1.conf中的值。
test2.conf内容如下:

[s1]
size=1000
len=500


[s2]
user=
passwd=

[s3]
size=150
count=3



Python脚本:
import configparser


cp1 = configparser.ConfigParser()
cp2 = configparser.ConfigParser()
cp1.read('test1.conf')
cp2.read('test2.conf')


sections = cp1.sections()


for section in sections:
    """
    print(section)
    print(cp.items(section))
    print(cp.items(section)[0][0])
"""
    print(section, cp1.items(section)[0][0], cp1.items(section)[0][1])
    cp2.set(section, cp1.items(section)[0][0], cp1.items(section)[0][1])


with open("test2.conf", "w+") as f:
    cp2.write(f)




执行脚本,test2.conf修改为:
[s1]
size=800
len=400


[s2]
user=root
passwd=root


[s3]
size=150
count=3






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值