[英]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.