Open In App

Handling TOML files using Python

Last Updated : 05 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will see how we can manipulate TOML files using tomli/tomlib module in Python.

What is a TOML file?

TOML stands for Tom’s Obvious, Minimal Language, here Tom refers to the creator of this language Tom-Preston Werner. It is a file format, especially for files that hold some kind of configuration details, due to obvious semantics that aims to be “minimal,” it is intended to be easy to read and write, and it is designed to map unambiguously to a dictionary. Its specification is open-source and receives contributions from the community. TOML is used in a variety of software projects and is implemented in a variety of programming languages.

Generic Syntax of a TOML file

TOML syntax is primarily composed of key = value pairs, [section names], and # (for comments). The syntax of TOML files is similar to that of.INI files, but it includes a formal specification, whereas the INI file format has many competing variants.

Its specification lists the following data types as supported: String, Integer, Float, Boolean, Datetime, Array, and Table.

Example of a simple TOML file:

The example is taken from the official TOML website.  Here, the owner, database, servers, etc are the Keys, and variables like name, dob, enabled, ports, etc are subkeys of the parent key – owner, database, etc. Sections like servers.alpha and servers.beta means that alpha and beta are subkeys of the main key servers. To access those we first need to call servers then alpha, we can’t directly call alpha or beta. It will throw an error.

# This is a TOML document

title = "TOML Example"

[owner]
name = "Tom Preston-Werner"
dob = 1979-05-27T07:32:00-08:00

[database]
enabled = true
ports = [ 8000, 8001, 8002 ]
data = [ ["delta", "phi"], [3.14] ]
temp_targets = { cpu = 79.5, case = 72.0 }

[servers]

[servers.alpha]
ip = "10.0.0.1"
role = "frontend"

[servers.beta]
ip = "10.0.0.2"
role = "backend"

Required Module:

For this tutorial we will need a library called Tomlib It was previously known as tomli, write the following command to install it.

pip install tomli

While importing we will import tomlib but while installing it is tomli, both are the same.

Stepwise Implementation:

For this tutorial, we will use the following TOML file from the official documentation. Later we will convert a text into TOML file which will be different than this one.

Create a file, copy-paste the below text, and save it with an extension .toml

# This is a TOML document.

title = "TOML Example"

[owner]
name = "Tom Preston-Werner"
dob = 1979-05-27T07:32:00-08:00 # First class dates

[database]
server = "192.168.1.1"
ports = [ 8000, 8001, 8002 ]
connection_max = 5000
enabled = true

[servers]

  # Indentation (tabs and/or spaces) is allowed but not required
  [servers.alpha]
  ip = "10.0.0.1"
  dc = "eqdc10"

  [servers.beta]
  ip = "10.0.0.2"
  dc = "eqdc10"

[clients]
data = [ ["gamma", "delta"], [1, 2] ]

# Line breaks are OK when inside arrays
hosts = [
  "alpha",
  "omega"
]

Opening a toml file

Firstly we will open and print an already existing toml file.

Python3




import tomllib
  
  
# Opening a Toml file using tomlib
with open("<entire_path_of_toml_file>","rb") as toml:
    toml_dict = tomllib.load(toml)
  
# Printing the entire fetched toml file
print(toml_dict)


Here we will open the toml file in read-binary mode and use the load method of tomlib. We will load and store that toml file into a variable and then normally print it.

Output:

{'title': 'TOML Example', 'owner': {'name': 'Tom Preston-Werner', 
'dob': datetime.datetime(1979, 5, 27, 7, 32, tzinfo=datetime.timezone(datetime.timedelta(days=-1, seconds=57600)))}, 
'database': {'server': '192.168.1.1', 'ports': [8000, 8001, 8002], 'connection_max': 5000, 'enabled': True}, 
'servers': {'alpha': {'ip': '10.0.0.1', 'dc': 'eqdc10'}, 'beta': {'ip': '10.0.0.2', 'dc': 'eqdc10'}}, 
'clients': {'data': [['gamma', 'delta'], [1, 2]], 'hosts': ['alpha', 'omega']}}

 

If we want to print a certain value of a certain key, just like the way we fetch using Dictionary in Python, we can do that by implementing the following code:

Python3




# Command - pip install tomli
import tomllib
  
  
# Opening a Toml file using tomlib
with open("<entire_path_of_toml_file>","rb") as toml:
    toml_dict = tomllib.load(toml)
  
# Fetching and printing particular value from toml file
print(toml_dict["clients"]["data"][0])


Output:

 

Convert a simple string into toml file:

Now we will convert a simple string into toml file using the toml formatting style. Copy and paste the following text and save it as a toml format.

Python3




import tomllib
  
txt = """
  
title = "GeeksforGeeks TOML"
  
[tutorials]
info = "Different Tutorials Available"
subjects = ["OS","DBMS","DSA","Cloud Computing"]
  
    [tutorials.OS]
    chapters = ["Deadlocks","CPU Scheduling","Process","Threading"]
  
    [DSA]
    linear = ["Stack","Queue","Linked List"]
  
    non_linear = ["Graph","Tree"]
[modern_tech]
  
subjects = ["AI","ML","DL"]
  
  
"""
  
toml_d = tomllib.loads(txt)
  
print(toml_d)


Inside the txt file, we are storing a string using the TOML formatting. Then inside the toml_d variable, we are converting that string into a toml file using the loads() method. It is like the operation we do by using JSON.

Output:

 

Handling errors related to TOML:

If someone tries to convert a simple string that is not being created by following the TOML structure and then uses the loads() method to convert it into toml we might face an error. So to handle this kind of error we will introduce try-except block with the exception named TOMLDecodeError.

Python3




import tomllib
  
try:
    toml_new = tomllib.loads("GeeksforGeeks")
    print(toml_new)
except tomllib.TOMLDecodeError:
    print("Wrong Format")


TOML files basically are a [key] = value pair like a dictionary, but here we have just passed a simple string that doesn’t follow the TOML formatting standard. That’s why it gave the following error.

Output:

 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads