-1

I have a program that uses a config file from the users local directory. If the local config file is missing some section or name, I want to update the local config file from the project config file. Only the missing section or name-value should be added, if there is an existing name-value, it should not be modified.

Local File:

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

[Ecal]
CalculateEField = False
CalculateEcfromI = False
OutputPVonly = False

Project File

[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

Result after copying: Local File

[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

Note that the existing value in the local file does not change. Any additional name-value pair should be added under the same section as present in the project config file.

I tried to use config parser in python but so far no success. I really appreciate if somebody could point me in correct direction.

FARAZ SHAIKH
  • 95
  • 1
  • 1
  • 7

1 Answers1

1

ConfigParser will give you the results you specify above. The order in which files are read matters, existing values will be replaced by those read in later.

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)
TBaggins
  • 62
  • 5