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.
I am quite new to scripting inside blender, but have a few insights in general python programming. Since Your Question is quite old and maybe awnsered elsewhere, I will fill in my awnser for any future visitor.
I noticed a few things:
Your variable filepath isn’t used, instead you repeat the filepath as Rawstring
The main problem with the filepath, despite not using the variable: You use a relative path. My first intuiton by reading your script was: Does the “csv”-file be saved to the project awnser?
Clear Awnser no: Instead it will be saved to the root directory of your blender installation.
Better Solution:
from pathlib import Path
ROOT = bpy.path.abspath("//") # Path there your blend file is saved
filepath = Path(ROOT) / "R1.csv"
The Object “R1” name is hard coded
This just depends how you want to achieve it, but hardcode things leads to typos
Instead read a list of all objects and use the index (this might lead to readability issues)
Or specify the Object as Global on top
Maybe your Object R1 is not the only instance of R1 and you have R1.001 R1.002 etc
This will fail the if statement.
you might be able in this case to achieve this with beginswith() method of the string class.