3

我是 Python 新手,想使用该ConfigParser模块读取配置文件。这是我的配置文件:

[Server]
server_name= localhost

这是我的代码:

#!/usr/bin/env python

import ConfigParser

config = ConfigParser.ConfigParser()
config.read=('config.cfg')

print config.get('Server', 'server_name')

我尝试运行它,它给了我错误:

    File "./read_config.py", line 10, in <module>
    print config.get('Server', 'server_name')
  File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/ConfigParser.py", line 531, in get
    raise NoSectionError(section)
ConfigParser.NoSectionError: No section: 'Server'

它找不到服务器部分。该config.cfg文件与 Python 脚本位于同一目录中,我什至给出了完整路径,但仍然出现相同的错误。我在 OSX 和 Debian 6 上都尝试过 Python 2.6 和 2.7。我在这里缺少什么?

4

1 回答 1

6

您在以下行中有一个额外的字符:

config.read('config.cfg')

我已经删除了=.

使用=,代码在语法上是有效的,但与预期的不同。

于 2012-02-10T12:16:50.573 回答