Save bone position and rotation in a .txt file

Hello guys!
I’m try create a script that get pose and rotation of bone and save in a .txt file. I want run the script up until to arrive on last frame of the scene, but in don’t know how to make this. I want too save the list and after skip a line, and do this successively until the frames are finished. This automation would help me a lot in my work. Can someone help me? Thanks fo any anwser. (Sorry my english!)

import bpy

arm = bpy.data.objects["Armature"]
end_ = bpy.data.scenes["Scene"].frame_end
frame_ = bpy.data.scenes["Scene"].frame_current

pose_list = []
rota_list = []

if frame_ < end_:
    for bone in arm.pose.bones:
        pos_ = bone.tail
        rot_ = bone.rotation_euler
        path = bpy.path.abspath("//Idle_animation.txt")
        file = open(path, "w")
        
        pos_text_0 = '"' + bone.name +  '"' + " : " + str(pos_).replace("Vector ", "Vector(") + ")"
        pos_text_1 = pos_text_0.replace("<", "")
        pos_text_2 = pos_text_1.replace(">", "")
        
        rot_text_0 = '"' + bone.name +  '"' + " : " + str(rot_).replace("Euler ", "Euler(") + ")"
        rot_text_1 = rot_text_0.replace("<", "")
        rot_text_2 = rot_text_1.replace(">", "")
        
        pose_list.append(pos_text_2)
        file.writelines("Idle_frame_" +  str(frame_) + " = {" + str(str(str(pose_list).replace("'", "")).replace("[", "")).replace("]", "") + "}")
        #file.writelines("Idle_frame" +  str(frame_) + " = [" + str(str(str(rot_text_0).replace("'", "")).replace("[", "")).replace("]", "") + "]")
        file.close()
        
print("Saving pose of frame " + str(frame_))

bpy.data.scenes["Scene"].frame_current += 1

Here it is, though I dont know if rotation_euler is the proper way. I got only 0,0,0 with it. Perhaps it would be tail.xyz instead, but any way just to have it working just going with quaternions.

import bpy

start_frame = 0
scene = bpy.data.scenes["Scene"]
armature = scene.objects["Armature"]
outputfile = bpy.path.abspath("C:\\Users\\yo\\Desktop\\animation.txt")

pose_list = []
rota_list = []
buffer = []

def export_bone(bone):
    pos = bone.tail
    rot = bone.rotation_quaternion # bone.tail.xyz ???
    # log and append to buffer
    msg = "{0}: ({1}, {2}, {3}) ({4}, {5}, {6}, {7})".format(
        bone.name,
        pos.x, pos.y, pos.z,
        rot[0], rot[1], rot[2], rot[3])
    print(msg)
    buffer.append(msg)

# loop all frames
print("Starting Export")
scene.frame_current = start_frame
while scene.frame_current < scene.frame_end:
    # log and append to buffer
    msg = "Current Frame {0}".format(scene.frame_current)
    print(msg)
    buffer.append(msg)
    
    # change frame
    scene.frame_current += 1

    # export all bones of armature
    for bone in armature.pose.bones:
        export_bone(bone)

# output buffer to file
with open(outputfile, "w") as f:
    f.write("\n".join(buffer))

1 Like