【发布时间】:2021-08-30 00:14:56
【问题描述】:
我想使用 Python 在 markdown 文件中读写 YAML frontmatter。我遇到了 ruamel.yaml 包,但无法理解如何将其用于此目的。
如果我有降价文件:
---
car:
make: Toyota
model: Camry
---
# My Ultimate Car Review
This is a good car.
首先,有没有办法在我的 python 代码中将 yaml 数据设置为变量?
第二,有没有办法给markdown文件中的yaml设置新的值?
第一个,我试过了:
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'])
但得到一个错误:
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
第二个,我试过了:
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'
但得到同样的错误错误:
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
【问题讨论】:
标签: python yaml ruamel.yaml