TOML, tomllib File Example
This page was last reviewed on Mar 1, 2024.
Dot Net Perls
Tomllib. Sometimes a custom configuration file format may be helpful, but more often, TOML files are a better choice. They support the most common needed features.
With tomllib, we can parse the sections, and key-value-pairs of a TOML file. Just one method, load, is needed to perform the parsing.
Example. This program loads a TOML file with tomllib. Please note that Python 3.12 is used—older versions of Python may not have tomllib available.
Step 1 We call open() in a with-statement to open an example file—the file contents are shown after the program here.
Step 2 We call tomllib.load() and pass the file object as an argument. This is where the parsing is done of the TOML file.
Step 3 In the TOML file, there is a "bird" section, and we can access this section like a key in a dictionary.
Step 4 Within the "bird" section, there are 2 key-value pairs, and we access these by their keys here.
Step 5 We access the other section in the TOML file, the "cat" section, in the same way as the "bird" section.
import tomllib # Step 1: open the file in a with-statement. with open("example.toml", "rb") as f: # Step 2: load the file. data = tomllib.load(f) print(data) # Step 3: access the bird section. bird = data["bird"] print("BIRD", bird) # Step 4: access 2 properties of the bird section. color = bird["color"] print("COLOR", color) size = bird["size"] print("SIZE", size) # Step 5: access the cat section and access its properties as well. cat = data["cat"] print("CAT", cat) color = cat["color"] print("COLOR", color) print("FRIENDLY", cat["friendly"])
[bird] color = "blue" size = 10 # Here is a comment. [cat] color = "orange" friendly = true
{'bird': {'color': 'blue', 'size': 10}, 'cat': {'color': 'orange', 'friendly': True}} BIRD {'color': 'blue', 'size': 10} COLOR blue SIZE 10 CAT {'color': 'orange', 'friendly': True} COLOR orange FRIENDLY True
While tomllib in Python can only parse TOML files, and not write them, it is still useful in reading config files. Often config files are meant to be edited by hand, and only parsed by the program.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Mar 1, 2024 (new).
© 2007-2024 Sam Allen.