Python配置解析器找不到部分? - 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()仅返回以下内容:“ []”

在使用相同的代码之前,我已经完成了这项工作,但现在无法正常工作。任何帮助将不胜感激。

python大神给出的解决方案

我总是使用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的文件,并根据需要指定完整路径,正如我已经评论过的那样。如果找不到文件,解析器将以静默方式失败。