Update field with ConfigParser -Python-

Francisco picture Francisco · Mar 15, 2011 · Viewed 15.5k times · Source

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')

Answer

accuya picture accuya · Nov 18, 2012
  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