[英]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 我正在尝试在python中使用ConfigParser从配置文件params.txt中读取一些值,但一直收到MissingSectionHeadError
I have a file params.txt: 我有一个文件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? 怎么了?
For some reason you are doing: 由于某些原因,您正在执行以下操作:
g.readline()
before passing the file to readfp
. 在将文件传递给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. 这将读取包含[all]
的行,因此,当SafeConfigParser
读取文件时,它将不会读取节标题,并且您会收到该错误。 To fix it simply don't call readline()
: 要解决它,只需不调用readline()
:
In [4]: parser = cp.SafeConfigParser()
...: with open('data.ini', 'r') as g:
...: parser.readfp(g)
...: print(parser.getfloat('all', 'zigzag'))
0.08
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.