简体   繁体   中英

How to append to existing config file using ConfigObj?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM