简体   繁体   English

如何使用 ConfigObj 将 append 到现有配置文件?

[英]How to append to existing config file using ConfigObj?

I am attempting to use ConfigObj to write to a config file with a function.我正在尝试使用ConfigObj写入带有 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.当调用 function createConfig()时,会写入配置文件,但是,如果脚本再次运行,它将覆盖之前创建的配置文件。 I want to preserve the previous entires and only add to the file, or overwrite if the same REFNAME is provided.我想保留以前的整体并仅添加到文件中,或者在提供相同的REFNAME时覆盖。

I'm having trouble understanding how to do this from the docs:我无法从文档中理解如何做到这一点:

https://configobj.readthedocs.io/en/latest/configobj.html 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.如果将设置文件的路径与create_empty=True参数一起传递给ConfigObj()初始化程序,它将仅在文件不存在时创建一个空文件,从而允许更新任何现有文件。

This is explained in the ConfigObj specifications section of the documentation where it describes what keyword arguments the method accepts.这在文档的ConfigObj 规范部分进行了解释,其中描述了该方法接受的关键字 arguments。

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.请注意,您可能希望将 function 的名称更改为openConfig() ,因为它现在就是这样做的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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