1

I am attempting to use ConfigObj to write to a config file with a function.

#!/usr/bin/evn python3.5

import configobj

def createConfig(path):
    config = configobj.ConfigObj()
    config.filename = path
    config[REFNAME] = {}
    config[REFNAME]['URL'] = URL
    config.write()

REFNAME = input("Enter a reference name :")
URL= input("Enter a URL :")

createConfig('server.ini')

When the function createConfig() is called the config file is written, however, if the script runs again it overwrites the config file created previously. I want to preserve the previous entires and only add to the file, or overwrite if the same REFNAME is provided.

I'm having trouble understanding how to do this from the docs:

https://configobj.readthedocs.io/en/latest/configobj.html

Any help would be appreciated.

wilbo
  • 21
  • 5
  • You need to provide a [mre] that can be run to reproduce the problem. – martineau Oct 17 '19 at 21:47
  • @martineau Thanks for the link, I reworked my question and provided a better example which you can use to reproduce the issue. – wilbo Oct 18 '19 at 20:30

1 Answers1

1

If you pass the path to the settings file to the ConfigObj() initializer along with a create_empty=True argument, it will create an empty file only when the file doesn't already exist—thereby allowing the any existing file to be updated.

This is explained in the ConfigObj specifications section of the documentation where it describes what keyword arguments the method accepts.

import configobj

def createConfig(path):
    config = configobj.ConfigObj(path, create_empty=True)
    config[REFNAME] = {}
    config[REFNAME]['URL'] = URL
    config.write()

REFNAME = input("Enter a reference name: ")
URL= input("Enter a URL: ")

createConfig('server.ini')

Note you might want to change the name of the function to openConfig() since that is what it now does.

martineau
  • 119,623
  • 25
  • 170
  • 301