简体   繁体   English

Python ConfigParser模块找不到部分

[英]Python ConfigParser module fails to find section

I'm using Python 2.6 to write in an .ini file, called config.ini. 我正在使用Python 2.6编写一个名为config.ini的.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: 到目前为止还可以,但是当我运行脚本(因此函数self.saveConfig('Config', 'testoption', 'True') ,出现NoSectionError异常:

ConfigParser.NoSectionError: No section: 'Config' ConfigParser.NoSectionError:无节:'Config'

Which seems pretty weird as I actually have this section. 当我实际有此部分时,这似乎很奇怪。

Here's my config.ini file: 这是我的config.ini文件:

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

I can read their values using the .get() method, but can not set different values. 我可以使用.get()方法读取它们的值,但不能设置其他值。 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. 但是, RawConfigParserread()方法RawConfigParser ,因为如果找不到文件,它不会引发异常-而是返回它设法读取的文件列表。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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