3

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.

chomes
  • 59
  • 7

1 Answers1

2

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()
toti08
  • 2,448
  • 5
  • 24
  • 36
  • 1
    Hi Toti08 Yes that was the problem after doing a bit more testing to it. I was thinking to myself why does append duplicate it but I started to understand the logic behind configparser in a sense it was reading the previous config information and would then write it all over again so it doesn't get lost. Thanks for this. – chomes Sep 11 '18 at 16:10