Handling TOML files using Python
Last Updated : 24 Apr, 2025
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:
Similar Reads
Writing to file in Python
Writing to a file in Python means saving data generated by your program into a file on your system. This article will cover the how to write to files in Python in detail. Creating a FileCreating a file is the first step before writing data to it. In Python, we can create a file using the following t
4 min read
File Handling in Python
File handling refers to the process of performing operations on a file such as creating, opening, reading, writing and closing it, through a programming interface. It involves managing the data flow between the program and the file system on the storage device, ensuring that data is handled safely a
7 min read
Unzipping files in Python
In this article we will see how to unzip the files in python we can achieve this functionality by using zipfile module in Python. What is a zip file ZIP file is a file format that is used for compressing multiple files together into a single file. It is used in an archive file format that supports l
3 min read
Find path to the given file using Python
We can get the location (path) of the running script file .py with __file__. __file__ is useful for reading other files and it gives the current location of the running file. It differs in versions. In Python 3.8 and earlier, __file__ returns the path specified when executing the Python command. We
5 min read
Using the Cat Command in Python
The cat command is a Linux shell command. It is the shorthand for concatenate. It is placed among the most often used shell commands. It could be used for various purposes such as displaying the content of a file on the terminal, copying the contents of a given file to another given file, and both a
4 min read
Read and Write TOML Files Using Python
TOML file stand for (Tom's Obvious, Minimum Language). The configuration files can be stored in TOML files, which have the .toml extension. Due to its straightforward semantics, which strives to be "minimal," it is supposed to be simple to read and write. It is also made to clearly map to a dictiona
6 min read
Working with zip files in Python
This article explains how one can perform various operations on a zip file using a simple python program. What is a zip file? ZIP is an archive file format that supports lossless data compression. By lossless compression, we mean that the compression algorithm allows the original data to be perfectl
5 min read
Read File As String in Python
Python provides several ways to read the contents of a file as a string, allowing developers to handle text data with ease. In this article, we will explore four different approaches to achieve this task. Each approach has its advantages and uses cases, so let's delve into them one by one. Read File
3 min read
Working with csv files in Python
Python is one of the important fields for data scientists and many programmers to handle a variety of data. CSV (Comma-Separated Values) is one of the prevalent and accessible file formats for storing and exchanging tabular data. In article explains What is CSV. Working with CSV files in Python, Rea
10 min read
Using C codes in Python | Set 1
Prerequisite: How to Call a C function in Python Let's discuss the problem of accessing C code from Python. As it is very evident that many of Pythonâs built-in libraries are written in C. So, to access C is a very important part of making Python talk to existing libraries. There is an extensive C p
4 min read