Duplicate section when adding a new option configparser

Viewed 858

When I add a new option to a section and write the file to config it always seems to duplicate the section and adds the new one with the new option.

Ideally I'd like to avoid this and only have one section, how do I achieve this?

Example occurrence

config.add_section("Install")
config.set("Install", "apt_installer", "True")
cfile = open("file.cfg", "w")
config.write(cfile)
cfile.close()

config.read("file.cfg")
config.set("Install", "deb_installer", "True")
cfile = open("file.cfg", "a")
config.write(cfile)
cfile.close()

When you open file.cfg it then has Install twice one with apt_installer and the other with both apt_installer and deb_installer. Any advice anyone can give I'd appreciate it.

1 Answers

I think the problem here is that you're opening your file in append mode. Try changing the line:

cfile = open("file.cfg", "a")

with

cfile = open("file.cfg", "w")

Also you should add the following lines:

import configparser

config = configparser.ConfigParser()

at the top in order to make your example working. So in the end your example should look like this:

import configparser

config = configparser.ConfigParser()
config.add_section("Install")
config.set("Install", "apt_installer", "True")
cfile = open("file.cfg", "w")
config.write(cfile)
cfile.close()

r = config.read("file.cfg")

config.set("Install", "deb_installer", "True")
cfile = open("file.cfg", "w")
config.write(cfile)
cfile.close()
Related