I really like how ruamel.yaml can Round-trip comments, but I haven't figured out how to remove a comment from a YAML file.
#!/usr/bin/env python3
from ruamel.yaml import YAML
import sys
yaml = YAML()
yaml.preserve_quotes = True
with open(sys.argv[1], 'r') as f:
object = yaml.load(f)
if sys.argv[2] == 'add':
object['key'] = "value"
object.yaml_add_eol_comment('Some comment', 'key')
if sys.argv[2] == 'remove':
# This line does not work: This method does not exist.
object.yaml_remove_eol_comment('key')
yaml.dump(object, open(sys.argv[1],'w'))
Other things I've tried
object.yaml_add_eol_comment('','key') # String index error.
object.yaml_add_eol_comment(' ', 'key') # This creates a comment like `# `.
object.yaml_add_eol_comment(None, 'key') # Error when trying to subscript it.
v = object['key']; del object['key']; object['key'] = v # The comment still sticks around.