How to call a YAML file in Python?
In Python, you can use the PyYAML library to parse and read YAML files. To start, you will need to install the PyYAML library by using the following command:
pip install pyyaml
After the installation is complete, you can use the following code to read and parse YAML files:
import yaml
# 读取YAML文件
with open('example.yaml', 'r') as file:
data = yaml.load(file, Loader=yaml.FullLoader)
# 访问YAML文件中的数据
print(data['key1'])
print(data['key2']['subkey1'])
In the above code, the YAML file is first opened using the open function and its content is read. The yaml.load function is then used to parse the content of the YAML file into a Python object. Finally, the data from the YAML file can be accessed by accessing the keys of the Python object.
Please note that the second parameter Loader=yaml.FullLoader is used to specify the use of the FullLoader loader to parse the YAML file, in order to avoid some security issues.