Python 配置解析器找不到部分? [英] Python Config Parser can't find section?
问题描述
我正在尝试使用 ConfigParser 为我的 pygame 游戏读取 .cfg 文件.由于某种原因,我无法让它发挥作用.代码如下所示:
I'm trying to use ConfigParser to read a .cfg file for my pygame game. I can't get it to function for some reason. The code looks like this:
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')
此文件中的 main 方法在游戏的启动器中调用.我已经测试过了,效果很好.当我运行此代码时,出现此错误:
The main method in this file is called in the launcher for the game. I've tested that out and that works perfectly. When I run this code, I get this error:
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'
问题是,有一个图形"部分.
The thing is, there is a section 'graphics'.
我试图读取的文件如下所示:
The file I'm trying to read from looks like this:
[graphics]
height = 600
width = 800
我已经确认它实际上被称为 options.cfg.config.sections() 只返回这个:"[]"
I have verified that it is, in fact called options.cfg. config.sections() returns only this: "[]"
在使用相同的代码之前我已经完成了这项工作,但现在无法工作.任何帮助将不胜感激.
I've had this work before using this same code, but it wont work now. Any help would be greatly appreciated.
推荐答案
我总是使用 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
的文件,并在需要时指定完整路径,正如我已经评论过的.如果没有找到文件,解析器将静默失败.
Also make sure there is a file called options.cfg
and specify the full path if needed, as I already commented. Parser will fail silently if there is no file found.
这篇关于Python 配置解析器找不到部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!