How to write a simple Wavefront-OBJ exporter in Python? Recently we were working to write our own software to load a Wavefront .OBJ file.

The file in question uses the .OBJ file format that Blender 2.73 and below generates which is like this:

# Blender v2.73 (sub 0) OBJ File: ''
# www.blender.org
o Cube_Cube.001
v -1.000000 -1.000000 1.000000
v -1.000000 -1.000000 -1.000000
v 1.000000 -1.000000 -1.000000
v 1.000000 -1.000000 1.000000
s off
f 1 2 3 4


The .OBJ exporter of Blender 2.74, in other hand, creates files like this, which are more closer to the definition that one will find in Wikipedia for example:

# Blender v2.74 (sub 0) OBJ File: ''
# www.blender.org
o Cube
v -1.000000 -1.000000 1.000000
v -1.000000 1.000000 1.000000
v -1.000000 -1.000000 -1.000000
v -1.000000 1.000000 -1.000000
vn -1.000000 0.000000 0.000000
vn 0.000000 0.000000 -1.000000
vn 1.000000 0.000000 0.000000
vn 0.000000 0.000000 1.000000
s off
f 2//1 4//1 3//1 1//1


While this is a valid OBJ file, its more involved to parse.

So, the problem is that I would like to write an exporter that uses just a subset of what the .OBJ file format can offer. In this case, just vertices and faces with everything in one line.

I would like to use python inside of Blender to do that but I have no idea on how to start to write this script.
This is a simple OBJ export script, that this writes valid OBJ files that load back into Blender: verts and faces, (no edges or materials).

import bpy
from bpy import context

filepath = "/tmp/simple_obj.obj"

obj = context.object
mesh = obj.data

with open(filepath, 'w') as f:
    f.write("# OBJ file\n")
    for v in mesh.vertices:
        f.write("v %.4f %.4f %.4f\n" % v.co[:])
    for p in mesh.polygons:
        f.write("f")
        for i in p.vertices:
            f.write(" %d" % (i + 1))
        f.write("\n")




This script can be pasted into Blenders text editor and executed, you will want to modify the output filepath.