TOML and YAML file formats are used to store configuration data for software applications. I have already discussed how to convert the toml format to yaml in Python. This article discusses how to convert yaml data to toml format in Python.
What is The YAML File Format?
YAML is a widely used data serialization format. We use the YAML file format for storing data in configuration files.
The YAML File format uses key-value pairs to represent data. Here, each pair consists of a key and a corresponding value. The key and value are separated by a colon (:) followed by a space. If there is a hierarchy in the data, we can represent it using nested key-value pairs and proper indentation.
For example, we can represent sample data in the YAML file format as shown below.
employee:
age: 35
name: John Doe
address:
city: San Francisco
state: CA
street: 123 Main St.
zip: 94102
job:
department: IT
title: Software Engineer
years_of_experience: 10
The above YAML string shows the data of an employee. It contains three outer keys namely employee
, address
, and job
.
- The
employee
key contains two nested keys namelyage
andname
to store the age and name of the employee. address
key contains four nested keys i.e.city
,state
,street
, andzip
to store the address details.- The
job
key contains three nested keys namelydepartment
,title
, andyears_of_experience
to store the job details.
What is The TOML File Format?
Just like YAML, TOML is also a configuration file format. It aims to provide a simple and intuitive way to store and organize configuration data.
The TOML format uses a syntax similar to the INI file format. Here, we store the data as key-value pairs using the assignment operator. Keys are on the left side of the equal sign (=), and values are on the right side. Values can be of various types, such as strings, numbers, booleans, and arrays.
The key-value pairs are organized into tables. Each table is defined using square brackets []. We can store as many key-value pairs in a table.
[employee]
age = 35
name = "John Doe"
[address]
city = "San Francisco"
state = "CA"
street = "123 Main St."
zip = 94102
[job]
department = "IT"
title = "Software Engineer"
years_of_experience = 10
In the above example, we have presented the same data given in the yaml string. As you can observe, the outer keys of the YAML data i.e. employee
, job
, and address
have been converted to table names in the toml file. The inner keys of the YAML file have been converted to key-value pairs in each table.
Both the toml and yaml file formats are popular formats for storing configuration data. However, we might sometimes need to convert the files from one format to another. In the next sections, we will discuss how to convert the yaml file format to toml in Python.
Convert YAML String to TOML String in Python
We will use the yaml and the toml module to convert a yaml string to a toml string. For this, we will first convert the yaml string to a Python dictionary using the load()
method defined in the yaml module. The load()
method takes the YAML string as its first input argument. It also takes a loader type as the input to the Loader
parameter. We will pass the literal SafeLoader
to the Loader
parameter. After execution of the load()
method, we will get a Python dictionary containing data from the YAML string.
Next, we will convert the Python dictionary to a toml string. For this, we will use the dumps()
method defined in the toml module. The dumps()
method takes the Python dictionary as its input argument and returns the output toml string. You can observe this in the following example.
import toml
import yaml
from yaml import SafeLoader
yaml_string="""address:
city: San Francisco
state: CA
street: 123 Main St.
zip: 94102
employee:
age: 35
name: John Doe
job:
department: IT
title: Software Engineer
years_of_experience: 10
"""
python_dict=yaml.load(yaml_string,Loader=SafeLoader)
toml_string=toml.dumps(python_dict)
print("The YAML string is:")
print(yaml_string)
print("The TOML string is:")
print(toml_string)
Output:
The YAML string is:
address:
city: San Francisco
state: CA
street: 123 Main St.
zip: 94102
employee:
age: 35
name: John Doe
job:
department: IT
title: Software Engineer
years_of_experience: 10
The TOML string is:
[address]
city = "San Francisco"
state = "CA"
street = "123 Main St."
zip = 94102
[employee]
age = 35
name = "John Doe"
[job]
department = "IT"
title = "Software Engineer"
years_of_experience = 10
Convert YAML String to a TOML File in Python
Instead of creating a string, we can also convert a yaml string to a toml file. For this, we will use the following steps.
- First, we will open an empty toml file in write mode using the
open()
function. Theopen()
function takes the file name as its first argument and the Python literal“w”
as its second input argument. After execution, it returns a file pointer. - Next, we will convert the yaml string to a Python dictionary using the
load()
method defined in the yaml module. - After this, we will use the
dump()
method defined in the toml module to save the dictionary to the file in toml format. For this, we will pass the dictionary as the first input argument and the file pointer to the toml file as the second argument. After execution, thedump()
method will write the data in toml format into the file. - Finally, we will close the file using the
close()
method.
After executing the above steps, the yaml string will be saved in the toml format into the file. You can observe this in the following example.
import toml
import yaml
from yaml import SafeLoader
yaml_string="""address:
city: San Francisco
state: CA
street: 123 Main St.
zip: 94102
employee:
age: 35
name: John Doe
job:
department: IT
title: Software Engineer
years_of_experience: 10
"""
toml_file=open("employee.toml","w")
python_dict=yaml.load(yaml_string,Loader=SafeLoader)
toml.dump(python_dict,toml_file)
toml_file.close()
The output file looks as follows.
YAML File to a TOML String in Python
Instead of a yaml string, we can also convert a yaml file to the toml format. For this, we will use the following yaml file.
To convert the yaml file to a toml string, we will use the following steps.
- First, we will open the yaml file in read mode using the
open()
function. - Next, we will read the yaml file into a Python dictionary. We will use the
load()
method defined in the yaml module for this. Theload()
method takes the file pointer to the yaml file as its first input argument andSafeLoader
as the input to theLoader
parameter. After execution, it returns a Python dictionary containing the data from the file. - Once we get the dictionary, we will convert it to a toml string using the
dumps()
method defined in the toml module. - Finally, we will close the yaml file using the
close()
method.
After executing the above steps, we can easily convert a yaml file to a toml string. You can observe this in the following example.
import toml
import yaml
yaml_file=open("employee.yaml","r")
python_dict=yaml.load(yaml_file,Loader=SafeLoader)
toml_string=toml.dumps(python_dict)
yaml_file.close()
print("The TOML string is:")
print(toml_string)
Output:
The TOML string is:
[address]
city = "San Francisco"
state = "CA"
street = "123 Main St."
zip = 94102
[employee]
age = 35
name = "John Doe"
[job]
department = "IT"
title = "Software Engineer"
years_of_experience = 10
Convert YAML File to TOML File in Python
To convert a yaml file to a toml file, we will first open the yaml file in read mode and an empty toml file in write mode using the open()
function. Then, we will read the yaml file into a Python dictionary using the load()
method defined in the yaml module. After this, we will write the data into the toml file using the dump()
method defined in the toml module.
Finally, we will close both files using the close()
method as shown below.
import toml
import yaml
yaml_file=open("employee.yaml","r")
toml_file=open("employee.toml","w")
python_dict=yaml.load(yaml_file,Loader=SafeLoader)
toml.dump(python_dict,toml_file)
toml_file.close()
yaml_file.close()
Conclusion
In this article, we discussed how to convert a yaml file or string to toml format in Python. To learn more about Python programming, you can read this article on list vs set in Python. You might also like this article on if vs elif vs else in python.
I hope you enjoyed reading this article. Stay tuned for more informative articles.
Happy Learning!
Recommended Python Training
Course: Python 3 For Beginners
Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.