Python配置分析器找不到节?

2024-04-18 21:15:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用ConfigParser为我的pygame游戏读取一个.cfg文件。因为某种原因我不能让它工作。代码如下所示:

import ConfigParser
def main():
    config = ConfigParser.ConfigParser()
    config.read('options.cfg')
    print config.sections()
    Screen_width = config.getint('graphics','width')
    Screen_height = config.getint('graphics','height')

此文件中的主方法在游戏的启动程序中调用。我已经测试过了,效果很好。运行此代码时,会出现以下错误:

Traceback (most recent call last):
  File "Scripts\Launcher.py", line 71, in <module>
    Game.main()
  File "C:\Users\astro_000\Desktop\Mini-Golf\Scripts\Game.py", line 8, in main
    Screen_width = config.getint('graphics','width')
  File "c:\python27\lib\ConfigParser.py", line 359, in getint
    return self._get(section, int, option)
  File "c:\python27\lib\ConfigParser.py", line 356, in _get
    return conv(self.get(section, option))
  File "c:\python27\lib\ConfigParser.py", line 607, in get
    raise NoSectionError(section)
ConfigParser.NoSectionError: No section: 'graphics'

问题是,有一个“图形”部分。

我试图读取的文件如下所示:

[graphics]
height = 600
width = 800

我已经验证了它,实际上叫做options.cfg。 config.sections()只返回以下内容:“[”

我以前用过同样的代码,但现在不行了。任何帮助都将不胜感激。


Tags: 文件代码inpyconfiggetmainline
2条回答

可能找不到您的配置文件。在这种情况下,解析器只会生成一个空集。您应该用检查文件来包装代码:

from ConfigParser import SafeConfigParser
import os

def main():
    filename = "options.cfg"
    if os.path.isfile(filename):
        parser = SafeConfigParser()
        parser.read(filename)
        print(parser.sections())
        screen_width = parser.getint('graphics','width')
        screen_height = parser.getint('graphics','height')
    else:
        print("Config file not found")

if __name__=="__main__":
    main()

我总是使用SafeConfigParser

from ConfigParser import SafeConfigParser

def main():
    parser = SafeConfigParser()
    parser.read('options.cfg')
    print(parser.sections())
    screen_width = parser.getint('graphics','width')
    screen_height = parser.getint('graphics','height')

还要确保有一个名为options.cfg的文件,并在需要时指定完整路径,正如我已经评论过的。如果找不到文件,解析器将自动失败。

相关问题 更多 >