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')
- open the config file
- read the content using ConfigParser
- close the file
- update the config, in memory now
- open the same file with w+
- write the updated in-memory content to the file
- 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
精彩评论