user10141085
user10141085

Reputation:

How do I edit a YAML file through python using ruamel.yaml and not pyyaml?

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

Upvotes: 2

Views: 7466

Answers (1)

Anthon
Anthon

Reputation: 76578

Assuming that the (unchanged) elastic.yml is your input, you can run:

import ruamel.yaml  

file_name = 'elastic.yml'
yaml = ruamel.yaml.YAML()

with open(file_name) as fp:
    data = yaml.load(fp)

data['cluster.name'] = 'BLABLABLABLABLA'
data['node.name'] = 'HEHEHEHEHEHEHE'

with open(file_name, 'w') as fp:
    yaml.dump(data, fp)

# display file
with open(file_name) as fp:
    print(fp.read(), end='')

to get the following output:

cluster.name: BLABLABLABLABLA

# Use a descriptive name for the node:
node.name: HEHEHEHEHEHEHE

Since the program displays the content of the file, you can be sure it has changed

Upvotes: 5

Related Questions