Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update field with ConfigParser -Python-

I thought that the set method of ConfigParser module updates the field given, but, it seems that the change remains only in memory and doesn't get into the config file. Is it a normal behaviour?

I have also tried the write method, but what I got was another replicated section which by so far is not what I want.

Here is a specimen which represents what I'm doing:

import sys
import ConfigParser 

   if __name__=='__main__':    
   cfg=ConfigParser.ConfigParser()
   path='./../whatever.cfg/..'
   c=cfg.read(path)
   print cfg.get('fan','enabled')
   cfg.set('fan','enabled','False')       
   c=cfg.read(path)
   print cfg.get('fan','enabled')
like image 403
Francisco Avatar asked Mar 14 '11 23:03

Francisco


2 Answers

  1. open the config file
  2. read the content using ConfigParser
  3. close the file
  4. update the config, in memory now
  5. open the same file with w+
  6. write the updated in-memory content to the file
  7. close the file
like image 86
accuya Avatar answered Sep 28 '22 01:09

accuya


from ConfigParser import SafeConfigParser
parser = SafeConfigParser()
parser.read('properties.ini')
dhana = {'key': 'valu11'}
parser.set('CAMPAIGNS', 'zoho_next_campaign_map', str(dhana))
with open("properties.ini", "w+") as configfile:
    parser.write(configfile)
like image 31
Dhanasekaran Anbalagan Avatar answered Sep 28 '22 02:09

Dhanasekaran Anbalagan