2013-08-06 45 views
2

我正在用python编写代码。我有以下数据的文件CONFG:使用ConfigParser在配置文件中添加新节不覆盖它

[section1] 
name=John 
number=3 

我使用configparser模块用来添加在这个已经存在的文件CONFG另一部分没有覆盖它。但是当我使用下面的代码:

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) 

它覆盖文件。我不想删除以前的数据。有什么办法可以只添加一个部分?如果我试着先写下前几节的数据,那么随着节数增加,它会变得不整齐。

+0

这是与ConfigParser一个问题,但根据上述[在此网站的一个问题](http://stackoverflow.com/questions/1134071/keep-configparser-output-文件排序#comment5138045_1134533),它应该在Python 2.7和3.1中修复。您可以尝试明确地设置'dict_type',如评论中所建议的那样。 –

+3

尝试以追加模式打开文件而不是写入?使用'a'而不是'w'? – Ben

+1

感谢本它工作:) – user2460869

回答

2

以附加模式而不是写入模式打开文件。使用'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)