Python Glossary Русский

all Python 3configparserterm

configparser.ConfigParser

parsers

The INI file parser: [section] headers, key = value pairs and %(name)s substitutions. The main class for reading and writing config files.

Syntax

parser = configparser.ConfigParser(defaults=None, *, interpolation=BasicInterpolation(), strict=True, allow_no_value=False)

Every value is stored and returned as a string: '5432' + 1 is a TypeError, and numbers come from getint(), getfloat() and getboolean() (the last accepts yes/no, on/off, true/false, 1/0). Keys are lowercased by optionxform, section names are not. Keys from [DEFAULT] show up in every section, including when you iterate over it. read() silently skips missing files and only returns the list of files it read, so check that list.

Examples

import configparser
cfg = configparser.ConfigParser()
cfg.read_string("[DEFAULT]\nDebug = yes\n[db]\nPort = 5432\n")
print(repr(cfg["db"]["port"]))  # → '5432' — строка, а не число
print(cfg.getint("db", "port") + 1)  # → 5433
print(cfg.getboolean("db", "debug"))  # → True — ключ пришёл из DEFAULT
print(list(cfg["db"]))  # → ['port', 'debug'] — ключи в нижнем регистре
import configparser
cfg = configparser.ConfigParser()
print(cfg.read(["missing.ini"]))  # → [] — файла нет, но ошибки тоже нет
print(cfg.sections())  # → []

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy