Python script to clean certain attributes in YAML files if they have specific values

This example script can be used to remove certain attributes from a YAML file’s entries in case they have certain default values.

#!/usr/bin/env python3
import yaml
import argparse
from pathlib import Path

def clean_yaml(data):
    if isinstance(data, dict):
        for key, value in list(data.items()):
            if key == 'offset3d' and (value == [0, 0, 0] or value == [0.0, 0.0, 0.0]):
                del data[key]
            elif key == 'rotate3d' and (value == [0, 0, 0] or value == [0.0, 0.0, 0.0]):
                del data[key]
            elif key == 'adhesivePos' and (value == [0, 0] or value == [0.0, 0.0]):
                del data[key]
            elif key == 'scale3d' and (value == [1, 1, 1] or value == [1.0, 1.0, 1.0]):
                del data[key]
            elif key == 'script3d' and value == '':
                del data[key]
            else:
                clean_yaml(value)
    elif isinstance(data, list):
        for item in data:
            clean_yaml(item)

def process_file(file_path):
    with open(file_path, 'r') as file:
        data = yaml.safe_load(file)

    clean_yaml(data)

    with open(file_path, 'w') as file:
        yaml.dump(data, file, default_flow_style=False)

def main():
    parser = argparse.ArgumentParser(description='Clean YAML files by removing offset3d and rotate3d if they are [0,0,0] or [0.0, 0.0, 0.0]')
    parser.add_argument('files', nargs='*', help='YAML files to process')

    args = parser.parse_args()

    if args.files:
        files = args.files
    else:
        files = list(Path('.').rglob('*.yaml'))

    for file_path in files:
        process_file(file_path)

if __name__ == "__main__":
    main()