简体   繁体   中英

Python ConfigParser module fails to find section

I'm using Python 2.6 to write in an .ini file, called config.ini. Here's my code:

def saveConfig(self, selection, value, bool):
    Config = ConfigParser.RawConfigParser()
    Config.read("config.ini")
    Config.set(selection, value, bool)
    with open('config.ini', 'w') as configfile:
        Config.write(configfile)

It's ok so far, but when I run my script (thus the function self.saveConfig('Config', 'testoption', 'True') , I get the NoSectionError exception:

ConfigParser.NoSectionError: No section: 'Config'

Which seems pretty weird as I actually have this section.

Here's my config.ini file:

[Config]
version = 0.1-unstable
testoption = False
testbool = True

I can read their values using the .get() method, but can not set different values. Ideas? Thanks in advance.

Your code works for me.

However, the RawConfigParser 's read() method is a little weird, in that it won't raise an exception if it can't find the file - instead it returns a list of the files it managed to read.

Try something like this...

def saveConfig(self, selection, value, bool):
    Config = ConfigParser.RawConfigParser()
    if not Config.read("config.ini"):
        raise IOError, 'cannot load config.ini'
    Config.set(selection, value, bool)
    with open('config.ini', 'w') as configfile:
        Config.write(configfile)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM