Reading TOML in Python

Last year I started hearing more about TOML, which is a markup language (like YAML, JSON, and XML) which reminds me of configparser. The nice thing about TOML is the syntax and formatting very closely resemble Python and Terraform syntax, so it’s a very natural thing to use and is worthwhile learning

To install the package via PIP:

sudo pip3 install tomli

On FreeBSD, use a package:

pkg install py39-tomli

Create some basic TOML in a “test.toml” file:

[section_a]
key1 = "value_a1"
key2 = "value_a2"

[section_b]
name = "Frank"
age = 51
alive = true

[section_c]
pi = 3.14

Now some Python code to read it:

import tomli
from pprint import pprint

with open("test.toml", mode="rb") as fp:
    pprint(tomli.load(fp))

When run, produces the following:

{'section_a': {'key1': 'value_a1', 'key2': 'value_a2'},
 'section_b': {'age': 51, 'alive': True, 'name': 'Frank'},
 'section_c': {'pi': 3.14}}

Leave a comment