Thursday, December 26, 2024
Google search engine
HomeLanguagesRead and Write TOML Files Using Python

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 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)
 
# Access values from the config
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
 
# Load a TOML file
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
 
# Load a TOML file
with open('config.toml', 'r') as f:
    config = toml.load(f)
 
# Modify values in the config
config['database']['level'] = 'information'
 
# Write the modified config back to the file
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”]

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments