Read and Write TOML Files Using Python
Last Updated :
24 Apr, 2025
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 dictionary. The TOML’s syntax primarily consists of key = value pairs. This makes TOML intended to be simple for people to read and create while simultaneously being clear and simple for computers to parse. Also, TOML is utilized as an alternative to other configuration files formats like JSON and YAML.
Required Module:
By executing the following command in your terminal or command prompt, you can use PIP to install the package.
pip install toml
TOML File Format
Key/value pairs, sections/tables, and comments make up the majority of TOML files, which also need to be valid UTF-8-encoded Unicode documents. The following data types are supported by TOML: String, Integer, Float, Boolean, Datetime, Array, and Table (hash table/dictionary). A case-sensitive language is TOML. Here’s a brief overview of the syntax for TOML files:
- Comments start with the # character and continue until the end of the line.
- Key-value pairs are represented as key = value and are separated by a new line.
- Keys can be nested using square brackets to create a hierarchy of sections, like [section1.subsection1].
- Values can be strings (in quotes), integers, floats, booleans, dates/times (in ISO 8601 format), arrays (in square brackets), or tables (in curly braces).
- Arrays can contain any type of value, including other arrays or tables.
- Tables represent a group of key-value pairs and can be used to group related configuration settings together. Tables can have their own sections and can be nested within other tables.
- Whitespace (spaces, tabs, and newlines) is significant in TOML files and should be used consistently to ensure that the file is parsed correctly.
UseCase of TOML Module
- Configuration files: TOML is often used as a configuration file format for Python applications. The toml module can be used to parse these configuration files and load the configuration data into the application.
- Data serialization: TOML can be used to serialize and deserialize Python data structures. The toml module provides methods for converting Python dictionaries to and from TOML data.
- Interoperability: TOML is a cross-language format, which means that TOML data can be easily shared between different programming languages. The toml module can be used to convert Python data structures to TOML, which can then be easily shared with other languages.
- Testing: TOML can be used as a test fixture format, allowing developers to write test cases in TOML format and use the toml module to load and run the test cases in Python.
Directory Structure :

Directory Structure
Creating a TOML file
Create a TOML file, copy-paste the below text, and save it with an extension .toml.
[server]
host = "localhost"
port = 8080
ssl = false
[database]
url = "mongodb://localhost:27017"
name = "mydb"
username = "myuser"
password = "mypassword"
level = "info"
Reading TOML File with Python
The toml.load() method reads the contents of the TOML file and returns the parsed data as a Python dictionary. The toml. dumps() method serializes the data back into TOML format and returns it as a string. Finally, the serialized TOML data is printed to the console using the print() method. This code can be used to read and modify configuration data stored in a TOML file, and then save the modified data back to the file by using the toml.dump() method.
app.py
Python3
import toml
with open ( 'config.toml' , 'r' ) as f:
config = toml.load(f)
print (config[ 'server' ][ 'host' ])
print (config[ 'server' ][ 'port' ])
print (config[ 'database' ][ 'username' ])
|
Output:

Terminal Output
Writing In TOML File with Python
The toml.load() method is then used to parse the contents of the file into a dictionary named config.The code then modifies a specific value in the config dictionary by adding a new key-value pair under the ‘database’ key. The new key is ‘level2’ and its value is ‘new added information’.Finally, the modified config dictionary is written back to the config.toml file using the toml.dump() method, which converts the dictionary to TOML format and writes it to the file. The file is opened in write mode, and the with statement ensures that it is closed properly after writing.
Python3
import toml
with open ( 'config.toml' , 'r' ) as f:
config = toml.load(f)
config[ 'database' ][ 'level2' ] = 'new added information'
with open ( 'config.toml' , 'w' ) as f:
toml.dump(config, f)
|
Output:
check config.toml file again
[server]
host = "localhost"
port = 8080
ssl = false
[database]
url = "mongodb://localhost:27017"
name = "mydb"
username = "myuser"
password = "mypassword"
level = "info"
level2 = "new added information"
Modifying TOML File with Python
The code first imports the toml library, which provides functions for loading and dumping TOML files using the the open() function to open the TOML configuration file called config.toml. The file is opened in read mode (‘r’) and its contents are loaded into a Python dictionary using the toml.load() function. The resulting dictionary, called config, contains the configuration data from the TOML file. The code then modifies a value in the config dictionary by changing the level value in the database section to ‘information’.
Finally, the modified config dictionary is written back to the config.toml file using the open() function again, this time in write mode (‘w’). The modified dictionary is written to the file using the toml.dump() function, which converts the dictionary to a TOML-formatted string and writes it to the file.
app.py
Python3
import toml
with open ( 'config.toml' , 'r' ) as f:
config = toml.load(f)
config[ 'database' ][ 'level' ] = 'information'
with open ( 'config.toml' , 'w' ) as f:
toml.dump(config, f)
|
Output:
Check your config.toml file again to see changes:
[server]
host = "localhost"
port = 8080
ssl = false
[database]
url = "mongodb://localhost:27017"
name = "mydb"
username = "myuser"
password = "mypassword"
level = "information"
Difference Between JSON and TOML file
Both Toml and JSON are effective in representing structured data, however, they differ in terms of data types, flexibility, and syntax. The format to select will depend on your project’s specific needs as well as the tools and libraries you’re utilizing.
- Syntax: JSON uses a syntax based on JavaScript object notation, while TOML uses a more human-readable syntax that is closer to a configuration file.
- Comments: TOML supports comments, whereas JSON does not.
- Data types: JSON supports a limited set of data types, including strings, numbers, booleans, arrays, and objects. TOML, on the other hand, supports a wider range of data types, including dates, times, and tables.
- Use cases: JSON is widely used for data interchange between web applications, APIs, and databases. TOML is often used for configuration files, such as in the case of the popular static site generator, Hugo.
Example:
JSON
| TOML
|
---|
{ “employee”: { “name”: “John Doe”, “age”: 35, “gender”: “male”, “address”: “123 Main St, Anytown USA”, “hobbies”: [“reading”, “cooking”, “hiking”], “skills”: { “programming_languages”: [“Python”, “Java”, “C++”], “databases”: [“MySQL”, “PostgreSQL”, “MongoDB”] } } } |
[employee] name = “John Doe” age = 35 gender = “male” address = “123 Main St, Anytown USA” hobbies = [“reading”, “cooking”, “hiking”]
[employee.skills] programming_languages = [“Python”, “Java”, “C++”] databases = [“MySQL”, “PostgreSQL”, “MongoDB”]
|
Similar Reads
Reading and Writing CSV Files in Python
CSV (Comma Separated Values) format is one of the most widely used formats for storing and exchanging structured data between different applications, including databases and spreadsheets. CSV files store tabular data, where each data field is separated by a delimiter, typically a comma. Python provi
4 min read
Reading and Writing XML Files in Python
Extensible Markup Language, commonly known as XML is a language designed specifically to be easy to interpret by both humans and computers altogether. The language defines a set of rules used to encode a document in a specific format. In this article, methods have been described to read and write XM
8 min read
Reading and Writing YAML File in Python
YAML (YAML Ain't Markup Language) is a human-readable data serialization standard that is commonly used for configuration files and data exchange between languages with different data structures. YAML is preferred in many cases due to its simplicity and readability compared to other formats like JSO
3 min read
Reading and Writing to text files in Python
Python provides built-in functions for creating, writing, and reading files. Two types of files can be handled in Python, normal text files and binary files (written in binary language, 0s, and 1s). Text files: In this type of file, Each line of text is terminated with a special character called EOL
8 min read
Reading and Writing JSON to a File in Python
The full form of JSON is Javascript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called JSON. To use this feature, we import the JSON package in Pytho
3 min read
Read JSON file using Python
The full form of JSON is JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called JSON. To use this feature, we import the JSON package in Pytho
4 min read
Reading and Writing lists to a file in Python
Reading and writing files is an important functionality in every programming language. Almost every application involves writing and reading operations to and from a file. To enable the reading and writing of files programming languages provide File I/O libraries with inbuilt methods that allow the
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
Handling TOML files using Python
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 o
5 min read
Python - Write Bytes to File
Files are used in order to store data permanently. File handling is performing various operations (read, write, delete, update, etc.) on these files. In Python, file handling process takes place in the following steps: Open filePerform operationClose file There are four basic modes in which a file c
2 min read