读取配置文件Python时的ConfigParser.MissingSectionHeaderError

时间:2014-07-18 11:21:22

标签: python configparser

我正在尝试使用Python中的ConfigParser从配置文件params.txt中读取一些值,但不断收到MissingSectionHeadError

我有一个文件params.txt:

[all]
zigzag = 0.08
fractal = 0.03
rng_length = 1000
stp = 100

和以下代码:

parser = cp.SafeConfigParser()
g = open(params, 'r')
g.readline()
parser.readfp(g)
print parser.getfloat('all', zigzag)

我收到此错误:

Traceback (most recent call last):
  File "deadrabbit_console_0-1.py", line 166, in <module>
    DRconsole().cmdloop()
  File "/usr/lib/python2.7/cmd.py", line 142, in cmdloop
    stop = self.onecmd(line)
  File "/usr/lib/python2.7/cmd.py", line 221, in onecmd
    return func(arg)
  File "deadrabbit_console_0-1.py", line 127, in do_load_data
    get_data(series, params)
  File "deadrabbit_console_0-1.py", line 115, in get_data
    parser.readfp(g)
  File "/usr/lib/python2.7/ConfigParser.py", line 324, in readfp
    self._read(fp, filename)
  File "/usr/lib/python2.7/ConfigParser.py", line 512, in _read
    raise MissingSectionHeaderError(fpname, lineno, line)
ConfigParser.MissingSectionHeaderError: File contains no section headers.
file: /home/baconwichsand/Documents/Dead Rabbit/params.txt, line: 1
'zigzag = 0.08\n'

怎么了?

1 个答案:

答案 0 :(得分:3)

出于某种原因,你正在做:

g.readline()

将文件传递给readfp之前。这将读取包含[all]的行,因此当SafeConfigParser读取文件时,它将读取节标题,并且您收到该错误。要解决此问题,请不要拨打readline()

In [4]: parser = cp.SafeConfigParser()
   ...: with open('data.ini', 'r') as g:
   ...:     parser.readfp(g)
   ...: print(parser.getfloat('all', 'zigzag'))
0.08