1

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

1
  • No it works. I think I didn't make myself quite clear. I add the if statement before cfg.set(). I guess that's what made you confuse. Commented Jul 1, 2011 at 3:28

1 Answer 1

5

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()
Sign up to request clarification or add additional context in comments.

3 Comments

I forgot to close the file. Thanks. Yes I'm reading an existing file. That's why I want to append new values to file. So should I read the existing file and write it again with new values?
If you write out the config file with your updates, all values you previously had will also exist, so yes.
Working fine with cfg file updation :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.