简体   繁体   中英

Change value in ini file using ConfigParser Python

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.

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)

I had an issue with: with open

Other way:

import configparser

def set_value_in_property_file(file_path, section, key, value):
    config = configparser.RawConfigParser()
    config.read(file_path)
    config.set(section,key,value)                         
    cfgfile = open(file_path,'w')
    config.write(cfgfile, space_around_delimiters=False)  # use flag in case case you need to avoid white space.
    cfgfile.close()

It can be used for modifying java properties file: file.properties

Below example will help change the value in the ini file:

PROJECT_HOME="/test/"
parser = ConfigParser()
parser.read("{}/conf/cdc_config.ini".format(PROJECT_HOME))
parser.set("default","project_home",str(PROJECT_HOME))


with open('{}/conf/cdc_config.ini'.format(PROJECT_HOME), 'w') as configfile:
    parser.write(configfile)
[default]
project_home = /Mypath/

Python's officialdocs on configparser illustrate how to read, modify and write a config-file.

import configparser

config = configparser.ConfigParser()
config.read('settings.ini')
config.set('SETTINGS', 'value','15')

with open('settings.ini', 'w') as configfile:
    config.write(configfile)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM