首页 > 解决方案 > 如何防止在编辑的 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 文件中)。

标签: ruamel.yaml

解决方案


您在data.yaml文件的根级别有一个序列,当您加载它时,您会在变量代码中获得一个列表。之后,您分配给该列表的一个项目,或者该列表中包含一个或多个项目的列表,code并且您需要做的是。appendextend

您不能真正做的另一件事是在使用outputwith 语句的参数时读取和写入相同的文件。写入不同的文件或从文件加载,然后将更新的结构转储到同一文件。

您还应该确保键值对之间有逗号,因为现在您的代码将无法运行。

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

推荐阅读