Search code examples
pythonyamlpyyaml

Save/dump a YAML file with comments in PyYAML


I have a yaml file that looks like this:

# The following key opens a door
key: value

Is there a way I can load and dump this data while maintaining the comment?


Solution

  • PyYAML throws away comments at a very low level (in Scanner.scan_to_next_token).

    While you could adapt or extend it to handle comments in its whole stack, this would be a major modification. Dumping (=emitting) comments seems to be easier and was discussed in ticket 114 on the old PyYAML bug tracker.

    As of 2023, the feature request about adding support for loading comments is still stalling.