YAML file update and delete using python?
<p>I have a YAML file and it looks like below</p>

<pre><code>test:
 - exam.com
 - exam1.com
 - exam2.com
test2:
 - examp.com
 - examp1.com
 - examp2.com
</code></pre>

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

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

<pre><code>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)
</code></pre>

<p>gives:</p>

<pre><code>test:
 - exam.com
 - exam2.com
test2:
 - examp.com
 - examp1.com  # want to insert after this
 - examp1.5
 - examp2.com
</code></pre>

<p>The <code>block_seq_indent=1</code> is necessary as by default <code>ruamel.yaml</code> will left align a sequence value with the key.Â¹</p>

<p>If you want to get rid of the comment in the output you can do:</p>

<pre><code>data['test2']._yaml_comment = None
</code></pre>

<hr>

<p>Â¹ <sub>This was done using <a href="https://pypi.python.org/pypi/ruamel.yaml" rel="nofollow">ruamel.yaml</a> a YAML 1.2 parser, of which I am the author.</sub></p>

python yaml pyyaml