我正在尝试使用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()只返回以下内容:“[”
我以前用过同样的代码,但现在不行了。任何帮助都将不胜感激。
可能找不到您的配置文件。在这种情况下,解析器只会生成一个空集。您应该用检查文件来包装代码:
我总是使用
SafeConfigParser
:还要确保有一个名为
options.cfg
的文件,并在需要时指定完整路径,正如我已经评论过的。如果找不到文件,解析器将自动失败。相关问题 更多 >
编程相关推荐