The configparser module in Python

From Jens' Hjørne
Revision as of 13:36, 20 April 2022 by Jens (talk | contribs) (Created page with "The official documentation for the configparser module can be found [https://docs.python.org/3/library/configparser.html here]. The current page is only meant as my comments to t...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

The official documentation for the configparser module can be found here. The current page is only meant as my comments to that page. For actual proper documentation of the module, please refer to official page.

DEFAULT and other section names

The official documentation mentions that default values will override fallback values, if the default value exist when get is called. But if you aren't reading the documentation serially, then you might not know, that default values is taken from the section named 'DEFAULT'.

If you create a section named by the empty string, it will display as precisely that, until the file is written to disk. When the file is written the key,value pairs in the section called [empty-string] will be written to the DEFAULT section, and an empty section, called [empty-string], will be created.

This means that this code:

import configparser as cp
conf = cp.ConfigParser()
conf[] = {'Int value 1': 42, 'String value 1': 'String value test', 'Float value 1': 3.1415}
with open('test.ini', 'w') as f:
    conf.write(f)

Will produce this file:

[DEFAULT]
int value 1 = 42
string value 1 = String value test
float value 1 = 3.1415

[]