ruamel.yaml - 如何防止在编辑的 yaml 文件中删除较早的列表值?
问题描述
这是我的 YAML 文件 ( data.yaml
):
- Department: "IT"
name: "abcd"
Education: "Bachlore of Engineering"
我想编辑它如下:
- Department: "IT"
name: "abcd"
Education: "Bachlore of Engineering"
- Department: "Production"
name: "xyz"
Education: "Bachlore of Engineering"
- Department: "Management"
name: "ab"
Education: "MBA"
这是我的代码(目前只添加第二个列表):
from pathlib import Path
from ruamel.yaml import YAML
from ruamel.yaml.scalarstring import SingleQuotedScalarString, DoubleQuotedScalarString
datapath= Path('C:/Users/Master 1TB/source/repos/check2/check2/data.yaml')
with YAML(output=datapath) as yaml:
yaml.indent(sequence=4, offset=2)
code = yaml.load(datapath)
code = [{
"Department": "Production"
"name": "xyz"
"Education": "Bachlore of Engineering"
}]
yaml.dump(code)
现在,当代码转储data.yaml
早期列表中的新列表时的问题被删除,因此我的输出是:
- Department: "Production"
name: "xyz"
Education: "Bachlore of Engineering"
相反,我希望前一个项目也在输出中,正如您在链接中解释的那样(如何读取 YAML 文件中的组件以便我可以使用 ruamel.yaml 编辑它的键值?),我必须附加新的列表值,但这只有在我有一个列表值时才有可能。
在这种情况下可以做什么?
此外,我将添加更多列表值data.yaml
(将所有早期列表保留在同一个 YAML 文件中)。
解决方案
您在data.yaml
文件的根级别有一个序列,当您加载它时,您会在变量代码中获得一个列表。之后,您分配给该列表的一个项目,或者该列表中包含一个或多个项目的列表,code
并且您需要做的是。append
extend
您不能真正做的另一件事是在使用output
with 语句的参数时读取和写入相同的文件。写入不同的文件或从文件加载,然后将更新的结构转储到同一文件。
您还应该确保键值对之间有逗号,因为现在您的代码将无法运行。
import sys
from pathlib import Path
from ruamel.yaml import YAML
from ruamel.yaml.scalarstring import SingleQuotedScalarString, DoubleQuotedScalarString
datapath = Path('data.yaml')
yaml = YAML()
code = yaml.load(datapath)
code.extend([{
"Department": "Production",
"name": "xyz",
"Education": "Bachlore of Engineering",
}])
yaml.dump(code, datapath)
print(datapath.read_text())
这使:
- Department: IT
name: abcd
Education: Bachlore of Engineering
- Department: Production
name: xyz
Education: Bachlore of Engineering
推荐阅读
- azure - 如何使用特定设置在 Azure 中自动部署 VM
- google-fit - 使用 google fit REST API 请求用户会话,只检索其中的几个
- javascript - GCP App Engine上的节点cron作业在周末不工作
- reactjs - 如何在全屏模式或反应中检测浏览器
- node.js - 如何订购包含模型计数的记录?
- android - 如何用活动结果 API 替换 startActivityForResult?
- regex - 使用 Go 删除 yaml 文件中与正则表达式匹配的行
- c# - 如何检索列表中的下一个更高的数字?
- c# - C# 中日文/中文字符的令牌无效或编译时错误
- chart.js - 在 ChartJS 上禁用 x 和 y 值的显示