This tutorials explains about Read and write to toml file in Python

TOML is a configuration format to store settings of an environment. You can check more about TOML .

toml is a python package, used to read and write from/to TOML file.

First install this library in a project using pip tool

pip install toml
E:\work\w3schools\python-examples>pip install toml
Collecting toml
  Downloading toml-0.10.2-py2.py3-none-any.whl (16 kB)
Installing collected packages: toml
Successfully installed toml-0.10.2

[notice] A new release of pip is available: 23.1.2 -> 23.3.1
[notice] To update, run: python.exe -m pip install --upgrade pip

Let’s see how to read and write to toml file from python

How to read the toml file in Python

Following are steps required to parse toml file in python.

  • After installation toml package, Import toml package in a code.
  • Open the file using open function, takes file name and opens in read mode(r)
  • It opens the file in read mode and filestr variable point to start of a file
  • toml.load() method reads the file into a variable data, It returns python dictionary.
  • data holds key and value pairs
  • Print the dictionary to console using print method
  • Dictionary values printed using square bracket with key using print method

Here is an example read-python.py:

import toml

# Reading the entire TOML file
with open('config.toml', 'r') as filestr:
    data = toml.load(filestr)
    print(data)
#
print(data['mysql']['host'])
print(data['mysql']['username'])
print(data['mysql']['password'])

After running the code in the terminal using py read-python.py command

E:\work\w3schools\python-examples> py read-python.py
{'mysql': {'host': 'localhost:31016', 'username': 'root', 'password': 'password', 'database': 'students'}}
localhost:31016
root
password

How to write to TOML file in Python

Please follow Steps required to write a python object into TOML file

  • Create a Python dictionary object.
  • Open the file in write mode
  • use toml.dump() method that takes object data and file pointer
  • On running the code, It creates result.toml file

Here is an example code

import toml

# Writing to a TOML file
data = {
    'mysql': {
        'host': 'localhost:31016',
        'username': 'root',
        'password': 'password',
        'database': 'students'
        }
    }

with open('result.toml', 'w') as file:
    toml.dump(data, file)

Please note:

It is an basic example on read and write operations on toml file in python. Handle exceptions during Input and output operations in the code.