How can I parse a YAML file in Python
To parse a YAML file in Python, you can use the yaml
library. Here is an example of how to parse a YAML file and access its data:
import yaml
with open("file.yaml", "r") as file:
data = yaml.safe_load(file)
print(data)
This example uses the safe_load()
function from the yaml
library to parse the contents of the YAML file and return the data as a Python object (such as a dictionary or list). The with open
block is used to open the file and automatically close it after the block is executed.
You can access the data in the YAML file using the familiar syntax of the python data structure that it was loaded into. For example, if the YAML file has a structure like this:
name: John age: 30 address: street: Main St city: Springfield state: IL zip: 62701
You can access the name, age, street, city, state, and zip in the following way:
print(data["name"]) # John
print(data["age"]) # 30
print(data["address"]["street"]) # Main St
print(data["address"]["city"]) # Springfield
print(data["address"]["state"]) # IL
print(data["address"]["zip"]) # 62701
Note that the yaml.safe_load()
function is used in this example to prevent malicious code from being executed if the YAML file contains any. The yaml.load()
function can also be used but it is not recommended as it can execute malicious code.