Python-Skript zum rekursiven Laden & erneuten Speichern von YAMLs

Dies kann verwendet werden, um zu beheben, dass PyYAML durch Formatierung leicht abweichende YAML-Dateien erzeugt als jede manuell erstellte Datei. Beispielsweise können Sie dieses Skript zuerst verwenden, um einen sauberen Diff nur durch erneutes Speichern zu erzeugen, und dann ein anderes Skript ausführen, um die YAML zu modifizieren, für einen saubereren Diff.

resave_yamls.py
#!/usr/bin/env python3
import argparse
import yaml
import pathlib

def load_and_save_yaml(file_path):
    with open(file_path, 'r', encoding='utf-8') as file:
        data = yaml.safe_load(file)
    with open(file_path, 'w', encoding='utf-8') as file:
        yaml.safe_dump(data, file)

def process_files(file_paths):
    for file_path in file_paths:
        try:
            load_and_save_yaml(file_path)
            print(f"Processed: {file_path}")
        except Exception as e:
            print(f"Failed to process {file_path}: {e}")

def main():
    parser = argparse.ArgumentParser(description="Load and re-save YAML files.")
    parser.add_argument('files', nargs='*', help="YAML files to process. If not provided, searches for all *.yaml files in the current directory and subdirectories.")
    args = parser.parse_args()

    if args.files:
        file_paths = [pathlib.Path(file) for file in args.files]
    else:
        file_paths = list(pathlib.Path('.').rglob('*.yaml'))

    process_files(file_paths)

if __name__ == "__main__":
    main()

Check out similar posts by category: Python