如何防止在编辑的 yaml 文件中删除较早的列表值?

How to prevent earlier list values from getting deleted in the edited yaml file?

这是我的 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"

相反,我希望输出中也包含前一项,正如您在 link ( ) 中所解释的那样,我必须附加新的列表值,但这只有在我有一个列表值。
在这种情况下可以做什么?
此外,我将在 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