Angom
Angom

Reputation: 763

How to update an existing section in python config file? (Python 3.6.6)

There are already many question related to the config file, most of them are for reading and writing a new Section. My question is related to updating an existing section.

My config file rg.cnf

[SAVELOCATION1]
outputpath1 = TestingPath
[SAVELOCATION2]
outputpath2 = TestingPath

Code to update the config file:

def updateConfigFile(fileName, textdata):
    config = configparser.ConfigParser()
    cnfFile = open(fileName, "w")
    config.set("SAVELOCATION2","outputpath2",textdata)
    config.write(cnfFile)
    cnfFile.close() 

Invoking the above method as:

updateConfigFile("rg.cnf","TestingPath2")    

Running the above code gives NoSectionError:

configparser.NoSectionError: No section: 'SAVELOCATION2'

Should config.set() be used only with config.add_section()? But that also does not work as it overwrites the whole file and I don't want to add any new section.

Is there any method to update the the section in the config file?

Upvotes: 1

Views: 1514

Answers (1)

jwodder
jwodder

Reputation: 57540

You need to load the config file into the ConfigParser before you can edit it:

def updateConfigFile(fileName, textdata):
    config = configparser.ConfigParser()
    config.read(fileName)  # Add this line
    cnfFile = open(fileName, "w")
    config.set("SAVELOCATION2","outputpath2",textdata)
    config.write(cnfFile)
    cnfFile.close() 

Upvotes: 1

Related Questions