正在将丢失的数据从一个配置文件复制到另一个



我有一个程序,它使用用户本地目录中的配置文件。如果本地配置文件缺少某些节或名称,我想从项目配置文件更新本地配置文件。只应添加缺少的节或名称值,如果存在现有的名称值,则不应修改该名称值。

本地文件:

[PowerPoint]
template = ppt Template.pptx
title info = User
Image directory = C:/Users/Someone/Desktop/here/
[Ecal]
CalculateEField = False
CalculateEcfromI = False
OutputPVonly = False

项目文件

[PowerPoint]
template = ppt Template.pptx
Title = Copy this
lot = Copy this too
title info = User2
Image directory = C:/Users/Someone_else/HomePC/nothere/
[Ecal]
CalculateEField = False
CalculateEcfromI = False
OutputPVonly = False
[New Section]
do nothing = okay

复制后的结果:本地文件

[PowerPoint]
template = ppt Template.pptx
Title = Copy this
lot = Copy this too
title info = User
Image directory = C:/Users/Someone/Desktop/here/
[Ecal]
CalculateEField = False
CalculateEcfromI = False
OutputPVonly = False
[New Section]
do nothing = okay

请注意,本地文件中的现有值不会更改。任何附加的名称-值对都应该添加到项目配置文件中的同一节下。

我尝试在python中使用配置解析器,但到目前为止没有成功。如果有人能给我指明正确的方向,我真的很感激。

ConfigParser将为您提供上面指定的结果。读取文件的顺序很重要,现有的值将被以后读取的值替换。

import configparser
cf = configparser.ConfigParser()
# Values from 'local' overwrite those from 'project'
cf.read(['project.ini', 'local.ini']) 
# Write combined config to file.
with open('result.ini', 'w') as f:
cf.write(f)

最新更新