baconwichsand
baconwichsand

Reputation: 1191

ConfigParser.MissingSectionHeaderError when reading config file Python

I am trying to read some values from a config file params.txt using ConfigParser in Python but keep getting a MissingSectionHeadError

I have a file params.txt:

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

and the following code:

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

where I am getting this error:

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'

What's wrong?

Upvotes: 2

Views: 8335

Answers (1)

Bakuriu
Bakuriu

Reputation: 101969

For some reason you are doing:

g.readline()

before passing the file to readfp. This will read the line containing [all] so when SafeConfigParser reads the file it will not read the section header, and you receive that error. To fix it simply don't call readline():

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

Upvotes: 3

Related Questions