How to use YAML in Python
Published on Aug. 22, 2023, 12:15 p.m.
To use YAML in Python, you can use the PyYAML library, which provides a way to read and write YAML files in Python. Here’s how you can use PyYAML in Python:
- Install PyYAML by running
pip install pyyaml
in your terminal or command prompt. - To read a YAML file, you can use the
yaml.load()
function in PyYAML. Here’s an example:
import yaml
with open("config.yml", "r") as f:
config = yaml.load(f, Loader=yaml.FullLoader)
In this example, we open a YAML file named config.yml
in read-mode using the open()
function. Then we use the yaml.load()
function to load the YAML data from the file and store it in a Python variable named config
. The Loader=yaml.FullLoader
argument is used to ensure the function uses the FullLoader, which is safer to use than the default one.
3. To write YAML data to a file, you can use the yaml.dump()
function in PyYAML. Here’s an example:
import yaml
data = {"name": "John", "age": 30, "city": "New York"}
with open("data.yml", "w") as f:
yaml.dump(data, f)
In this example, we create a YAML-compatible dictionary called data
. Then we open a new file named data.yml
in write-mode using the open()
function. Finally, we use the yaml.dump()
function to write the data
dictionary to the file.
working with lists in YAML with PyYAML
To expand on my previous answer, when working with lists in YAML with PyYAML, you can use the square bracket syntax to define a list, like this:
fruits:
- apple
- banana
- orange
In Python, you can use PyYAML’s yaml.load()
method to load the YAML data into a Python dictionary, like this:
import yaml
# Load YAML data from a string
yaml_data = """
fruits:
- apple
- banana
- orange
"""
data = yaml.load(yaml_data, Loader=yaml.FullLoader)
# Print the list of fruits
print(data["fruits"])
In this example, we first define some YAML data as a string. We then use PyYAML’s yaml.load()
method to parse the YAML data and convert it into a Python dictionary. Finally, we use the dictionary to print the list of fruits to the console.
Alternatively, you can use yaml.dump()
to write lists into a YAML file. For example:
import yaml
# Define a list of fruits
fruits = ["apple", "banana", "orange"]
# Write the list to a YAML file
with open("fruits.yml", "w") as f:
yaml.dump({"fruits": fruits}, f)
In this example, we define a list of fruits and use yaml.dump()
to write the list to a YAML file named fruits.yml
.