I want to change only the attribute anotherName from the following yaml file with python.
test.yaml:
---
kind: test
scope: not far
spec:
test1:
options:
- name: test.com
anotherName: example.com
empty: []
groupOne: []
emptyList:
firstList: []
secondList: []
Code (based on this answer)
import yaml
with open("test.yaml", 'r') as stream:
try:
loaded=yaml.safe_load(stream)
except yaml.YAMLError as exc:
print(exc)
temp= loaded['spec']['test1']['options']
for elem in temp:
elem['anotherName']='somethingChanged'
with open("modified.yaml", 'w') as stream:
try:
yaml.dump(loaded, stream)
print(loaded)
except yaml.YAMLError as exc:
print(exc)
The value has been changed, but the code change the order and the structure of the modified.yaml :
#First it misses the thre dashes
kind: test
scope: not far
spec:
test1:
emptyList:
firstList: []
secondList: []
groupOne: []
options:
- anotherName: somethingChanged #then the order is changed
empty: []
name: test.com