Skip to content

Instantly share code, notes, and snippets.

@shatil
Last active December 10, 2025 18:51
Show Gist options
  • Select an option

  • Save shatil/70b7c8be9e7b7912fbdf0385e234b884 to your computer and use it in GitHub Desktop.

Select an option

Save shatil/70b7c8be9e7b7912fbdf0385e234b884 to your computer and use it in GitHub Desktop.
Format YAML with Python 3rdparty module ruamel.yaml to preserve comments and quotes
#!/usr/bin/env python3
import argparse
import io
import ruamel.yaml
if __name__ == "__main__":
p = argparse.ArgumentParser()
p.add_argument("fp", default=[], nargs="+", help="files to format")
args = p.parse_args()
y = ruamel.yaml.YAML()
y.preserve_quotes = True
y.width = 1024
for fp in args.fp:
buf = io.StringIO()
with open(fp, "r+") as f:
d = y.load(f)
f.seek(0)
y.dump(d, f)
f.truncate()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment