Export keyframes coordinates as CSV file.


I have a script here that exports coordinates from all frames into CSV file. However, I’m trying to extract only the coordinates on keyframes, but not all frames. I have tried searching on various forums but have no luck so far.

    import bpy
    import csv
    from itertools import chain
    filepath = "R1.csv"
    with open(r"R1.csv",'w', newline='', encoding='utf-8') as file:
        csv_writer = csv.writer(file, dialect='excel')
        scene = bpy.context.scene
        frame_current = scene.frame_current
        for frame in range(scene.frame_start, scene.frame_end + 1):
            for ob in scene.objects:
                if "R1" in ob.name:
                    mat = ob.matrix_world
                    loc = mat.translation.yxz
                    csv_writer.writerow(tuple(chain((frame, ob.name), (loc.x, loc.y, loc.z))))

I’d be very grateful for some guidance, thank you very much.