2

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)
Paul
  • 1,101
  • 1
  • 11
  • 20
  • Please show your existing code. – S3DEV Aug 02 '21 at 18:35
  • 1
    You don't need the quote (usually). As long as you're producing correct, equivalent YAML the formatting shouldn't matter. See the accepted answer to this question for details: https://stackoverflow.com/questions/19109912/yaml-do-i-need-quotes-for-strings-in-yaml – Woodford Aug 02 '21 at 18:42
  • thank you @Woodford ! that's awesome to know. I will check it out; – Paul Aug 02 '21 at 18:47

1 Answers1

1

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.

flyx
  • 35,506
  • 7
  • 89
  • 126