user9198016
user9198016

Reputation:

ConfigParser section creation

If config.add_section('main') from ConfigParser is executed multiple times, targeting same file will that cause an error like having multiple main sections or it will just skip creating section if it already exists?

Upvotes: 2

Views: 1749

Answers (2)

Jean-François Fabre
Jean-François Fabre

Reputation: 140316

ConfigParser object can be seen as a dictonary (section) of dictionaries (option/option values).

Using add_section twice on the same name raises an exception

import configparser

s = configparser.ConfigParser()
s.add_section("main")
s.add_section("main")

gives:

configparser.DuplicateSectionError: Section 'main' already exists

workaround check if section exists, add only if it doesn't:

def add_section_no_matter_what(s,section_name):
   if not s.has_section(section_name):
      s.add_section(section_name)

useful in an helper function to create section if not already exists, else use the existing one.

Upvotes: 1

phihag
phihag

Reputation: 288298

Quoting the documentation of configparser.ConfigParser.add_section:

add_section(section) Add a section named section to the instance. If a section by the given name already exists, DuplicateSectionError is raised.

Upvotes: 2

Related Questions