Usage of Pyyaml
Pyyaml is a YAML parsing library for the Python language. It can convert YAML formatted data into Python objects, as well as convert Python objects into YAML format. The following are the basic steps for using Pyyaml:
Install Pyyaml
Enter the following command in the terminal to install Pyyaml:
pip install pyyaml
Convert YAML to Python objects
import yaml
#take YAML convert formatted data to Python object
with open('example.yaml', 'r') as f:
data = yaml.safe_load(f)
Convert Python objects to YAML
import yaml
#take Python object conversion to YAML format
data = {'name': 'John', 'age': 30}
yaml_data = yaml.dump(data)
Using Pyyaml to read and write YAML files
import yaml
#read YAML file
with open('example.yaml', 'r') as f:
data = yaml.safe_load(f)
#modify data
data['name'] = 'Alice'
#write YAML file
with open('example.yaml', 'w') as f:
yaml.dump(data, f)
It should be noted that safe_load(f) is a function in the Pyyaml library used to load YAML formatted data from input streams (such as files) into Python objects
It can safely load YAML files to avoid security vulnerabilities when loading malicious YAML files
Compared to the load function, the safe_load function has more restrictions and does not allow loading Python objects or instances of any class.