【问题标题】:Adding new section in config file without overwriting it using ConfigParser在配置文件中添加新部分而不使用 ConfigParser 覆盖它
【发布时间】:2013-08-08 01:36:35
【问题描述】:

我正在用 python 编写代码。我有一个包含以下数据的配置文件:

[section1]
name=John
number=3

我正在使用 ConfigParser 模块在这个已经存在的配置文件中添加另一个部分而不覆盖它。但是当我使用下面的代码时:

config = ConfigParser.ConfigParser()
config.add_section('Section2')
config.set('Section2', 'name', 'Mary')
config.set('Section2', 'number', '6')
with open('~/test/config.conf', 'w') as configfile:
    config.write(configfile) 

它会覆盖文件。我不想删除以前的数据。有什么办法可以再添加一个部分吗?如果我尝试先获取和写入前面部分的数据,那么随着部分数量的增加,它会变得不整齐。

【问题讨论】:

  • 那是 ConfigParser 的问题,但根据a question on this site,它应该在 Python 2.7 和 3.1 中修复。您可以尝试按照评论中的建议明确设置dict_type

标签: python append


【解决方案1】:

以追加模式而不是写入模式打开文件。使用“a”而不是“w”。

例子:

config = configparser.RawConfigParser({'num threads': 1})
config.read('path/to/config')
try:
    NUM_THREADS = config.getint('queue section', 'num threads')
except configparser.NoSectionError:
    NUM_THREADS = 1
    config_update = configparser.RawConfigParser()
    config_update.add_section('queue section')
    config_update.set('queue section', 'num threads', NUM_THREADS)

    with open('path/to/config', 'ab') as f:
        config_update.write(f)

【讨论】:

    【解决方案2】:

    您只需在代码之间添加一条语句。

    config.read('~/test/config.conf')
    

    例子:

    import configparser
    
    config = configparser.ConfigParser()
    config.read('config.conf')
    config.add_section('Section2')
    config.set('Section2', 'name', 'Mary')
    config.set('Section2', 'number', '6')
    with open('config.conf', 'w') as configfile:
        config.write(configfile)
    

    当我们读取我们想要追加的配置文件时,它会使用我们文件中的数据初始化配置对象。然后在添加一个新部分时,这些数据被附加到配置中......然后我们将这些数据写入同一个文件。

    这可以是附加到配置文件的一种方式。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-30
      • 2016-08-02
      • 1970-01-01
      • 2022-01-22
      • 2015-04-29
      • 2018-12-13
      • 2013-06-02
      相关资源
      最近更新 更多