Sign up ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free.

How can I check if the ConfigParser mainfile has a section or not,

And if it don´t then add a new section to it?

I am trying with this code:

import ConfigParser

config = ConfigParser.ConfigParser()

#if the config file don´t has the section 'globel', then add it to the config-file 
if not config.has_section("globel"):                                
       config.set("globel", "settings", "someting")
       config.write(open("/tmp/myfile.conf", "w"))

       print "The new sestion globel is now added!!"
#else just return the the value of globle->settings
       print "else... globle->settings == "+config.get("globel", "settings")
share|improve this question

1 Answer 1

up vote 3 down vote accepted

You need to read the config file before checking for the section. Put the line"/tmp/myfile.conf")

just after

config = ConfigParser.ConfigParser()

It's no error if the config file doesn't exist yet.

share|improve this answer
Cool thanks Florian :) – Voidcode Jul 8 '12 at 20:55

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.