Harley Holcombe Harley Holcombe - 4 months ago 56
Python Question

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?

Answer

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 is already being discussed.