Search code examples
pythonpython-3.xdictionaryconfig

How to customize a config file as specified by the values of a directory


I have a configuration file which has some lines commented out with a '#' which looks like this.

#year=1889
#model=foo
#size=small
working=y

Now I get some variables from another place in the code which are stored in a dictionary. Values that appear in the config should be commented in and, if necessary, adjusted to their value

mydict = {
  "model":"bar",       # <- uncommented+adjusted
  "size":"small",      # <- uncommented
  "working":"y",       # <- untouched
  "newValue":"new"     # <- not added
}

The file should look something like this, after it was edited:

#year=1889
model=bar
size=small
working=y

Solution

  • Technically you could do it by loading your config file line by line, checking if value is present in dict and if so replacing values and uncommenting like that:

    new_lines =[]
    with open(config_path, "r") as file:
      for line in file:
        name = line.split('=')[0].replace('#', '')
        if name in my_dict:
          new_lines.append(f'{name}={my_dict[name]}')
        else:
          new_lines.append(line)
    

    Then you could write it to config file:

      with open(config_path, "w") as file:
        for line in new_lines:
          file.write(line + "\n")
    

    But I think the better way would be just to use your dictionary as a config and in case of missing parameter checking in config file (it should be less messy).