Python configparser修改配置文件

来源:互联网 发布:mac最新系统版本10.13 编辑:程序博客网 时间:2024/05/22 10:22

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

[s1]size=800len=400[s2]user=rootpasswd=root




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

[s1]size=1000len=500[s2]user=passwd=[s3]size=150count=3



Python脚本:
import configparsercp1 = 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=800len=400[s2]user=rootpasswd=root[s3]size=150count=3