Change value in ini file using ConfigParser Python

后端 未结 3 1446
我在风中等你
我在风中等你 2021-02-05 14:20

So, I have this settings.ini :

[SETTINGS]

value = 1

And this python script

from ConfigParser import SafeConfigParser

parser =         


        
相关标签:
3条回答
  • 2021-02-05 15:01

    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

    0 讨论(0)
  • 2021-02-05 15:09

    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/
    
    0 讨论(0)
  • 2021-02-05 15:26

    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)
    
    0 讨论(0)
提交回复
热议问题