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.
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.
open()
in a with-statement to open an example file—the file contents are shown after the program here.tomllib.load()
and pass the file object as an argument. This is where the parsing is done of the TOML file.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.