I am looking for help to insert keyframes with python into my blender project. I already know, that it is possible to export keyframes via python. So it should be also possible to insert keyframes via python.

I wish to insert via python a data like a .xyz file [Xposition Yposition Zposition]. After that I would like to have a finished (camera)path in blender. Is there a way?

Thank you already!


1 Answer 1


I'm no developper but I managed to create a function that adds a specific keyframe on an object in Python.

It goes in 4 steps :

  1. check for animation data on the object (if none, create some)
  2. check for fcurve on the desired parameter (if none, create some)
  3. create the keyframe
  4. set the interpolation and easing for the keyframe

Blender NEEDS proper animation data and fcurve in order to add keyframes, any less and he'll look at you funny, spamming errors in the console.

Here's the code, with the 2 functions that handles the animation_data and fcurve check, and an example of the function in use :

def create_animation_data(target, name):
    if target.animation_data == None:
        target.animation_data.action = bpy.data.actions.new(name=name)    
def create_fcurve(target, data_path, id):
     fcurve = target.animation_data.action.fcurves.find(data_path=data_path, index=id)
     if fcurve == None:
          fcurve = target.animation_data.action.fcurves.new(data_path=data_path, index=id)
     return fcurve

def set_kf_object(obj, data_path="location", id=2, val=0, frame=0, interpolation="BEZIER", easing="EASE_IN"):
     #if no data, create animation data, new action, and new fcurve
     create_animation_data(obj, data_path)
     #store the fcurve
     fcurve = create_fcurve(obj, data_path, id)
     #insert the keyframe
     key = fcurve.keyframe_points.insert(frame=frame,value=val)
     #set interpolation and easing
     key.interpolation = interpolation
     key.easing = easing
#create a location keyframe on the Z axis, with a value of 1, at frame 36
#set the interpolation to 'CUBIC' and the easing to 'EASE_OUT'
cube = bpy.data.objects['Cube']
set_kf_object(cube, "location", 2, 1, 36, "CUBIC", "EASE_OUT")

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .