How to write a simple OBJ exporter with Python?(With Normals and UV) So i've been trying to write an OBJ exporter, to learn how Python and scripting for Blender in general works, i'm pretty new to Python scripting. I successfully managed to export vertices and polygons, but i can't export normals. Here is my code, i wrote it on top of the Template Exporter that comes with Blender, this is the exporting part of the code:

import bpy 
def write_some_data(context, filepath, use_some_setting):
print("running write_some_data...")
f = open(filepath, 'w', encoding='utf-8')
sce = bpy.context.scene
for ob in sce.objects:
{
    if ob.type == 'MESH':
    {
            dats = ob.data
            c = 0
            for vert in dats.vertices:
            {
                f.write( 'v %f %f %f\n' % (vert.co.x, vert.co.y, vert.co.z))
            }
            for face in dats.polygons:
            {
                for vert in face.vertices:
                {
                    c += 1
                    vnor = dats.vertices[vert].normal
                    f.write( 'vn %f %f %f\n' % (vnor.x, vnor.y, vnor.z) )
                }
                f.write('f')
                cuv = 0
                for vert in face.vertices:
                {
                    f.write( ' %i//%i' % (vert + 1, c + cuv) )
                    cuv += 1
                }
                f.write('\n') 
            }
    }
}
f.close()
return {'FINISHED'}


The normals are all in random order when importing and i can't fix it.
Okay, thanks to lemon for this answer:


  If I remember well, vertex normals are not at the "face level" but at the "vertex level" in OBJ. So you should export them the same way you did for 'v', outside of the polygons loop 


I added this code in the vertex loop:

f.write( 'vn %f %f %f\n' % (vert.normal.x,vert.normal.y,vert.normal.z))

And used the same index for both the vertices and normals in the face definitions and it imports correctly!