简体   繁体   中英

ruamel.yaml removing comments from output YAML

I have the following Python code:

import ruamel.yaml

source = open("source.yaml", "r")
target = open("target.yaml", "r")

sourceValues = ruamel.yaml.load(source, ruamel.yaml.RoundTripLoader, preserve_quotes=True)
targetValues = ruamel.yaml.load(target, ruamel.yaml.RoundTripLoader, preserve_quotes=True)

source.close()
target.close()

# some changes on target properties
targetValues['test']['something'] = sourceValues['test']['something']

with open('target.yaml', 'w') as conf:
  ruamel.yaml.dump(targetValues, conf, ruamel.yaml.RoundTripDumper)

One example of YAML with comments:

test:
  # some comment
  something: "something" # another comment
  else: 123

The above code outputs:

test:
  something: "something-updated"
  else: 123456

Everything works fine, fields are updated as expected, quotes are being kept, code indentation looks OK... But the comments are being lost.

You are using functions from the ruamel.yaml library that were deprecated quite a long time ago.

Your input round-trips without a problem:

import sys
from pathlib import Path
import ruamel.yaml

file_in = Path('target.yaml')
file_in.write_text("""\
test:
  # some comment
  something: "something" # another comment
  else: 123
""")
    
yaml = ruamel.yaml.YAML()
yaml.preserve_quotes = True
data = yaml.load(file_in)
yaml.dump(data, sys.stdout)

as this gives:

test:
  # some comment
  something: "something" # another comment
  else: 123

And this works even if you update data :

data['test']['something'] = 'something-updated'
yaml.dump(data, file_in)
print(file_in.read_text(), end='')

which gives:

test:
  # some comment
  something: "something-updated" # another comment
  else: 123

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM