Reputation: 1431
I am attempting to update a YAML file where I have a series of key, value pairs that look like
key:
'A': 'B'
'C': 'D'
I clear the file with f.truncate(0)
and then dump a dictionary back but when dumping the dictionary the key,values don't have the string quotes between key-value pairs. How would I get the dump back to the file to render string quotes?
edit: adding code
with open(filepath, "r+") as f:
d = yaml.unsafe_load(f)
# edit dictionary
# clear file
f.seek(0)
f.truncate(0)
yaml.dump(d, f, default_flow_style=False, sort_keys=False)
Upvotes: 2
Views: 1071
Reputation: 39688
You can keep the original style by avoiding to load the YAML content into native Python objects:
import yaml,sys
input = """
key:
'A': 'B'
'C': 'D'
"""
events = yaml.parse(input)
yaml.emit(events, sys.stdout)
print("---")
node = yaml.compose(input)
yaml.serialize(node, sys.stdout)
This code demonstrates using the event API (parse
/emit
) to load and dump YAML events, and the node API (compose
/serialize
) to load and dump YAML nodes. The output is
key:
'A': 'B'
'C': 'D'
---
key:
'A': 'B'
'C': 'D'
As you can see, the scalar style is preserved both times. Of course this is inconvenient if you want to edit the content, you will need to walk the event/node structure to do that. This answer shows how to implement a simple API to append stuff to your YAML using the event API.
For more information about why and when style information is lost when loading YAML into native structures, see this question.
Upvotes: 1