Ivan
Ivan

Reputation: 31069

ConfigParser problem Python

I'm having problem to append to config file. Here's what I want to create;

[section1]
val1 = val2
val3 = val4

but when I run the following code I see ConfigParser.NoSectionError: No section: 'section1'

import ConfigParser

cfg = ConfigParser.RawConfigParser()
cfg.set("section1", "val1", "val2")

f = open("example.cfg", "a")
cfg.write(f)

If I add

if not cfg.has_section("section1"):
    cfg.add_section("section1")

and then, this is what I get;

[section1]
val1 = val2

[section1]
val3 = val4

Could someone point me what I'm doing wrong? Thanks

Upvotes: 1

Views: 3843

Answers (1)

Doug Parrish
Doug Parrish

Reputation: 71

I fleshed out the code you put up a bit. Are you reading the existing file before checking for the section? Also, you should be writing the whole file at once. Don't append.

import ConfigParser

cfg = ConfigParser.ConfigParser()
cfg.read('example.cfg')

if not cfg.has_section('section1'):
    cfg.add_section('section1')

cfg.set('section1', 'val1', 'val2')
cfg.set('section1', 'val2', 'val3')

f = open('example.cfg', 'w')
cfg.write(f)
f.close()

Upvotes: 5

Related Questions