1

I have a YAML file and it looks like below

test:
 - exam.com
 - exam1.com
 - exam2.com
test2:
 - examp.com
 - examp1.com
 - examp2.com

I like to manage this file using python. Task is, I like to add an entry under "test2" and delete entry from "test".

Anthon
  • 69,918
  • 32
  • 186
  • 246
Manzoor
  • 85
  • 1
  • 3
  • 10
  • load the data into a python dictionary using the yaml library.. add / delete as you would from a regular python dict / list. write the original file – Haleemur Ali Aug 26 '16 at 13:30
  • Possible duplicate of http://stackoverflow.com/questions/28557626/how-to-update-yaml-file-using-python – Dinesh Pundkar Aug 26 '16 at 14:00

1 Answers1

1

You first have to load the data, which will give you a top-level dict (in a variable called data in the following example), the values for the keys will be lists. On those lists you can do the del resp. insert() (or append())

import sys
import ruamel.yaml

yaml_str = """\
test:
 - exam.com
 - exam1.com
 - exam2.com
test2:
 - examp.com
 - examp1.com  # want to insert after this
 - examp2.com
"""

data = ruamel.yaml.round_trip_load(yaml_str)
del data['test'][1]
data['test2'].insert(2, 'examp1.5')
ruamel.yaml.round_trip_dump(data, sys.stdout, block_seq_indent=1)

gives:

test:
 - exam.com
 - exam2.com
test2:
 - examp.com
 - examp1.com  # want to insert after this
 - examp1.5
 - examp2.com

The block_seq_indent=1 is necessary as by default ruamel.yaml will left align a sequence value with the key.¹

If you want to get rid of the comment in the output you can do:

data['test2']._yaml_comment = None

¹ This was done using ruamel.yaml a YAML 1.2 parser, of which I am the author.

Anthon
  • 69,918
  • 32
  • 186
  • 246