Python: Create config files with configparser

Python: Create config files with configparser
Photo by Artturi Jalli / Unsplash

Configparser is a simple, built-in way to start using config files in your Python scripts and programs.

Imagine our config.ini file looks like this:

[DEFAULT]
site_ranking = 5
site_speed = 5

[example_section]
url = yourawesome.site
port = 443
site_ranking = 10

Getting started is a simple as:

import configparser

config = configparser.ConfigParser()
config.read('config.ini')

Now we can access items much like we're using a dictionary, e.g. config['example_section']['url'] would return yourawesome.site. You can address one section directly (useful if you only have one section in the file):

>>> es = config['example_section']
>>> es['site_ranking']
10

The get method can also be used, which allows for fallback values: config.get('example_section', ‘not_port', fallback='9000') would return 9000.

The DEFAULT section provides values when keys do not exist in our example_section — even with a fallback value, the default value takes precedence:

>>> config.get('example_section', 'site_speed', fallback='10')
5

The return values will always be strings, unless methods like getint(), getfloat(), getboolean() are used. For booleans, values in the config file can be: 0, 1, no, yes, false, true.

Things to note:

  • Keys are not case sensitive, but values are
  • Values are assigned to keys with : or =
  • DEFAULT values have precedence over fallback values
  • Strings are returned by default for all values

Please let me know if you have some useful 'getting started' tips for Configparser!



Great! Next, complete checkout for full access to techbits.io
Welcome back! You've successfully signed in
You've successfully subscribed to techbits.io
Success! Your account is fully activated, you now have access to all content
Success! Your billing info has been updated
Your billing was not updated