簡體   English   中英

在配置文件中添加新部分而不使用 ConfigParser 覆蓋它

[英]Adding new section in config file without overwriting it using ConfigParser

我正在用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) 

它會覆蓋文件。 我不想刪除以前的數據。 有什么辦法可以只添加一個部分嗎? 如果我嘗試先獲取和寫入前面部分的數據,那么隨着部分數量的增加,它會變得不整潔。

以追加模式而不是寫入模式打開文件。 使用“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)

您只需要在代碼之間添加一條語句。

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)

當我們讀取要追加的配置文件時,它會使用文件中的數據初始化配置對象。 然后在添加新部分時,這些數據會附加到配置中……然后我們將這些數據寫入同一個文件。

這可以是附加到配置文件的方法之一。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM