Change value in ini file using ConfigParser Python

2019-04-07 10:21发布

问题:

So, I have this settings.ini :

[SETTINGS]

value = 1

And this python script

from ConfigParser import SafeConfigParser

parser = SafeConfigParser()
parser.read('settings.ini')

print parser.get('SETTINGS', 'value')

As you can see, I want to read and then replace the value "1" by another one. All I was able to do so far is to read it. I searched on the net how to replace it but I didn't find.

回答1:

As from the examples of the documentation:

https://docs.python.org/2/library/configparser.html

parser.set('SETTINGS', 'value', '15')


# Writing our configuration file to 'example.ini'
with open('example.ini', 'wb') as configfile:
    parser.write(configfile)