1

This is my YAML file (data.yaml):

  - Department: "IT"
    name: "abcd"
    Education: "Bachlore of Engineering"

And I want to edit it as follows:

  - Department: "IT"
    name: "abcd"
    Education: "Bachlore of Engineering"
  - Department: "Production"
    name: "xyz"
    Education: "Bachlore of Engineering"
  - Department: "Management"
    name: "ab"
    Education: "MBA"

This is my code (currently adding only second list):


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)

Now the problem when code dump the new list in the data.yaml the earlier list gets deleted, hence my output is:

  - Department: "Production"
    name: "xyz"
    Education: "Bachlore of Engineering"

Instead I want the previous item also in the output and as you explained in the link (How to read a component in YAML file so that I can edit it's key value using ruamel.yaml? ), I have to append the new list value, but this is possible only if I have one list value.
What can be done in this scenario?
Also I am going to add more list values in data.yaml (preserving all the earlier list in the same YAML file).

Anthon
  • 69,918
  • 32
  • 186
  • 246
MEHUL SOLANKI
  • 47
  • 3
  • 10

1 Answers1

0

You have a sequence at the root level of your data.yaml file, and when you load that you get a list in your variable code. After that you assigne to code and what you need to do is append an item to that list, or extend that list with a list of one or more items.

The other thing you cannot really do is have the same file for reading and writing when you use the output parameter to the with statement. Either write to a different file or load from the file then dump the updated structure to the same file.

You should also make sure you have commas between the key-value pairs, as it is now your code will not run.

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())

which gives:

- Department: IT
  name: abcd
  Education: Bachlore of Engineering
- Department: Production
  name: xyz
  Education: Bachlore of Engineering
Anthon
  • 69,918
  • 32
  • 186
  • 246