I found similar questions here on StackOverflow, but when I tried to implement the code [Anthons's response] to suit my situation, I noticed that it does not actually edit the YAML file. Also, I need to use ruamel.yaml, not PyYAML. Many of the answers I've reviewed use PyYAML.
import sys
import ruamel.yaml
yaml = ruamel.yaml.YAML()
# yaml.preserve_quotes = True
with open('elastic.yml') as fp:
data = yaml.load(fp)
data['cluster.name'] = 'BLABLABLABLABLA'
data['node.name'] = 'HEHEHEHEHEHEHE'
yaml.dump(data, sys.stdout)
This code outputs the file with the correct edits, however, when I actually go into the file (elastic.yml
), the original documentation is unchanged.
This is my first experience with ruamel.yaml and I would rather stick with this because I've noticed PyYAML does not keep comments.
The YAML file after I run the python code:
cluster.name: my-application
# Use a descriptive name for the node:
node.name: HappyNode
The output to the console after I run the python code:
cluster.name: BLABLABLABLABLA
# Use a descriptive name for the node:
node.name: HEHEHEHEHEHEHE
I've tried adding this to the bottom of the code to assure it write to the file, as described here:[Matheus Portela's response] but I get no luck:
with open('elastic.yml', 'w') as f:
yaml.dump(data, f)
I get the following error:
data['cluster.name'] = 'BLABLABLABLABLA'
TypeError: 'NoneType' object does not support item assignment