【问题标题】:How can I update config file with libconfig?如何使用 libconfig 更新配置文件?
【发布时间】:2018-08-10 11:09:46
【问题描述】:

如何使用 libconfig 更新配置文件? 我想更新而不删除文件的其他内容

https://pypi.python.org/pypi/libconf

例如

RTL_test: {
  My_model : {
     tests = ["test1","test2","test3","test4"];
     ignore = ["test2"];
};
};

cfg['RTL_test']['My_model']['ignore']='' 

【问题讨论】:

    标签: python python-3.x libconfig


    【解决方案1】:

    libconf.dump(cfg, f):

    import libconf
    
    # read
    with open('example.cfg') as f:
      config = libconf.load(f)
    
    config['RTL_test']['My_model']['ignore'] = 'updated'
    
    # write
    with open('example.cfg', 'w') as f:
      libconf.dump(config, f)      
    

    其他内容(如 cmets)在设计上会丢失,如果不修改 libconf 包的源,就无法保留它们。您可能想寻找其他包或解决方案,例如编写自己的序列化器/反序列化器。

    【讨论】:

    • 但是 example.cfg 有其他键。当我写时,其他键被删除。我也想保存 cmets @Yannic Hamann
    • 请澄清并更新您的问题。您现在唯一要问的是如何更新配置文件。这正是我的代码正在做的事情。
    • 为什么?我想更新而不删除文件的其他内容。 @Yannic Hamann
    • 答案是:不修改libconf的来源是不可能的,信息会被设计丢失。
    • 仅适用于特定情况,例如静态键还是高度动态的?如果后者肯定会超出 SO 问题的范围。无论如何,询问regex 是一个单独的问题,因为您明确询问如何使用libconf 实现这一目标。
    猜你喜欢
    • 2015-07-06
    • 2014-09-21
    • 2021-09-22
    • 1970-01-01
    • 2018-05-15
    • 2012-05-10
    • 1970-01-01
    • 1970-01-01
    • 2010-11-23
    相关资源
    最近更新 更多