I want to use Python to read and write YAML frontmatter in markdown files. I have come across the ruamel.yaml package but am having trouble understanding how to use it for this purpose.
If I have a markdown file:
---
car:
make: Toyota
model: Camry
---
# My Ultimate Car Review
This is a good car.
For one, is there a way to set the yaml data to variables in my python code?
Second, is there a way to set new values to the yaml in the markdown file?
For the first, I have tried:
from ruamel.yaml import YAML
import sys
f = open("cars.txt", "r+") # I'm really not sure if r+ is ideal here.
yaml = YAML()
code = yaml.load(f)
print(code['car']['make'])
but get an error:
ruamel.yaml.composer.ComposerError: expected a single document in the stream
in "cars.txt", line 2, column 1
but found another document
in "cars.txt", line 5, column 1
For the second, I have tried:
from ruamel.yaml import YAML
import sys
f = open("cars.txt", "r+") # I'm really not sure if r+ is ideal here.
yaml = YAML()
code = yaml.load(f)
code['car']['model'] = 'Sequoia'
but get the same error error:
ruamel.yaml.composer.ComposerError: expected a single document in the stream
in "cars.txt", line 2, column 1
but found another document
in "cars.txt", line 5, column 1