MissingSectionHeaderError:文件不包含节标题。(configparser)

时间:2016-10-03 12:42:44

标签: python python-2.7 configuration configuration-files configparser

我正在使用configparser来自动读取和修改名为'streamer.conf'的文件。 我这样做:

import configparser

config = configparser.ConfigParser()
config.read('C:/Users/../Desktop/streamer.conf')

然后它突然出现此错误消息:

MissingSectionHeaderError: File contains no section headers.
file: 'C:/Users/../Desktop/streamer.conf', line: 1
u'input{\n'

可能有什么问题?任何帮助表示赞赏。

5 个答案:

答案 0 :(得分:2)

只需指定正确的编码

config.read(config_file_path, encoding='utf-8-sig')
  • “utf-8-sig”适用于带BOM的UTF-8
  • “utf-8”适用于没有BOM的UTF-8

答案 1 :(得分:1)

我在创建pip.conf文件时收到了相同的错误消息。在我的情况下,我无意中创建了一个带BOM(字节顺序标记)的UTF-8文件,而不是普通的UTF-8文件(没有BOM)。

因此,请检查以确保您有纯文本文件。如果您不确定,可以在十六进制编辑器中打开文件并检查第一个字节。

答案 2 :(得分:1)

ConfigParser使用BOM解析UTF-8文件(xef xbb xbf)

    u = open("setting.ini").read().decode("utf-8-sig").encode("utf-8")
    fp = tempfile.TemporaryFile()
    fp.write(u)
    fp.seek(0)

    conf = ConfigParser.ConfigParser()
    conf.readfp(fp)

答案 3 :(得分:0)

您没有包含streamer.conf,但是从错误消息中看,它的格式不正确。 configparser用于解析" INI"文件:

[section1]
setting1 = value
setting2 = value

[section2]
setting3 = value
setting1 = value

答案 4 :(得分:0)

如其他答案中所述,配置文件必须为INI format,但您看到的实际错误是由于所请求的配置文件缺少任何标头-这些是用方括号括起来的名称,它们为INI文件的一部分提供了标题。默认标题为[DEFAULT],例如

[DEFAULT]
 config_item1='something'
 config_item2=2