开发者

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


  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


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)


Yes, it is normal that set operates on the information in memory rather than on the file from which the information was originally read.

write ought to be what you want. How exactly did you use it, what exactly did it do, and how did that differ from what you wanted?

Incidentally, you should generally be using ConfigParser.SafeConfigParser rather than ConfigParser.ConfigParser unless there's a specific reason for doing otherwise.

Moving forward with Python 3.x SafeConfigParser will be merged/renamed as ConfigParser so SafeConfigParser will eventually be deprecated and phased out.


I ran into the same issue and figure out that this worked for me:

def update_system_status_values(file, section, system, value):
    config.read(file)
    cfgfile = open(file, 'w')
    config.set(section, system, value)
    config.write(cfgfile)
    cfgfile.close()

1) Read it

2) Open it

3) Update it

4) Write it

5) Close it

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜