'Searching and writing in YAML file with python
I have a YAML file and it has multi-document in one file.
type: ABC
api_version: v3
metadata:
created_by: xxx
name: cccc
namespace: zzz
spec:
check_hooks: none
command: bbbbb
---
type: ABC
api_version: v3
metadata:
labels:
aaaa.io: xxx
created_by: me
name: xxx
namespace: aaaa
spec:
check_hooks: null
command: qqqq
- I want to read the file
- Then I want to add one more key-value pair under the "labels" object
- If labels object is not under metadata I want to add "labels" and then add underneath key-value pair
I have this code to load the multi-document file
with open(filepath) as stream:
for data in yaml.safe_load_all(stream):
print(data)
I am able to read file and print the dict object in the console. I am not sure what to do next. I am using ruamel.yaml library.
Solution 1:[1]
You are using ruamel.yaml
's old, deprecated API and you really should not for
a new program. Assuming your YAML is in the file input.yaml
do:
import sys
from pathlib import Path
import ruamel.yaml
in_file = Path('input.yaml')
yaml = ruamel.yaml.YAML()
insert_labels_at_front = True
labels = 'labels'
key = 'mykey'
val = 'myvalue'
all_docs = []
for data in yaml.load_all(in_file):
if 'metadata' in data:
md = data['metadata']
if labels not in md:
if insert_labels_at_front:
md.insert(0, labels, {key, val})
else:
md[labels] = {key: val}
all_docs.append(data)
yaml.dump_all(all_docs, sys.stdout) # replace sys.stdout with some output Path() instance
which gives:
type: ABC
api_version: v3
metadata:
labels: !!set
mykey:
myvalue:
created_by: xxx
name: cccc
namespace: zzz
spec:
check_hooks: none
command: bbbbb
---
type: ABC
api_version: v3
metadata:
labels:
aaaa.io: xxx
created_by: me
name: xxx
namespace: aaaa
spec:
check_hooks:
command: qqqq
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Anthon |