Last active
December 10, 2025 18:51
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/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