python - 读取配置文件时出现 ConfigParser.MissingSectionHeaderError Python

标签 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'

出了什么问题?

最佳答案

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

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

关于python - 读取配置文件时出现 ConfigParser.MissingSectionHeaderError Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24823854/

相关文章:

python - 使用 daa 深度处理大堆栈

python - Python 3 中的 configparser 中的 read 和 read_file 有什么区别?

python - ConfigParser 中的列表

python - 如何使用不同的 View 进行 django 注册?

python - 有向无环图的哈希值

python - 如何防止数据在 matplotlib 散点图中拥挤在一起?

python - stderr(来自 GDAL)未显示在 Python shell 中

Python configparser 不会接受没有值的键

python - 在database.ini文件中找不到节postgresql

python - 如何在配置文件中存储格式化字符串?