Update field using ConfigParser -Python-

I thought the set method of the ConfigParser module updates the specified field, but it seems that the change remains only in memory and does not fall into the configuration file. Is this normal behavior?

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

Here is a sample that represents what I am 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') 
+4
source share
4 answers
  • open configuration file
  • read content using ConfigParser
  • close file
  • update configuration, currently
  • open the same file with w +
  • write updated content in memory to a file
  • close file
+9
source

Yes, it is normal that set works with information in memory, and not with the file from which the information was originally read.

write should be what you want. How exactly did you use it, what exactly did it, and how did it differ from what you wanted?

By the way, you should usually use ConfigParser.SafeConfigParser and not ConfigParser.ConfigParser unless there is a specific reason for this.

Moving forward with Python 3.x SafeConfigParser will be merged / renamed to ConfigParser , so SafeConfigParser will eventually be deprecated and will be canceled.

+3
source
 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) 
0
source

I ran into the same problem and found 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 down

5) Close it

0
source

Source: https://habr.com/ru/post/1343701/


All Articles