Python Glossary Русский

all Python 3configparserexception

configparser.MissingSectionHeaderError

exceptions

Raised when a file starts with key = value without a [section] header. A subclass of ParsingError.

Syntax

except configparser.MissingSectionHeaderError as e: e.lineno, e.line

This is how reading .env-like or properties files fails: configparser requires a section before the first key. The old trick is to prepend a header yourself: read_string('[root]\n' + text). Since 3.13 there is allow_unnamed_section=True with the configparser.UNNAMED_SECTION key.

Examples

import configparser
text = "debug = yes\nport = 8000\n"
try:
    configparser.ConfigParser().read_string(text)
except configparser.MissingSectionHeaderError as e:
    print(e.lineno, repr(e.line))  # → 1 'debug = yes\n'
cfg = configparser.ConfigParser()
cfg.read_string("[root]\n" + text)
print(cfg.getint("root", "port"))  # → 8000
# Python 3.13+
import configparser
cfg = configparser.ConfigParser(allow_unnamed_section=True)
cfg.read_string("debug = yes\n")
print(cfg.getboolean(configparser.UNNAMED_SECTION, "debug"))  # → True

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy