Export keyframes coordinates as CSV file.

Hello,

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')
        csv_writer.writerow(("frame","object","locX","locY","locZ"))
    
        scene = bpy.context.scene
        frame_current = scene.frame_current
    
        for frame in range(scene.frame_start, scene.frame_end + 1):
            scene.frame_set(frame)
            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))))
    
        scene.frame_set(frame_current)

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