Reading and writing binary STL files with Numpy

I’ve since written a library to replace this script and add more functionality such as reading/writing both binary and ascii STL files. See the blog post here

After seeing Sukhbinder’s implementation of reading STL files with Numpy I thought it would be a nice thing to have a simple STL class to both read and write the binary files.

import struct
import numpy

class Stl(object):
    dtype = numpy.dtype([
        ('normals', numpy.float32, (3, )),
        ('v0', numpy.float32, (3, )),
        ('v1', numpy.float32, (3, )),
        ('v2', numpy.float32, (3, )),
        ('attr', 'u2', (1, )),

    def __init__(self, header, data):
        self.header = header = data

    def from_file(cls, filename, mode='rb'):
        with open(filename, mode) as fh:
            header =
            size, = struct.unpack('@i',
            data = numpy.fromfile(fh, dtype=cls.dtype, count=size)
            return Stl(header, data)

    def to_file(self, filename, mode='wb'):
        with open(filename, mode) as fh:

if __name__ == '__main__':
    # Read from STL file
    stl = Stl.from_file('test.stl')

    # Increment the X axis by one['v0'][:, 0] += 1['v1'][:, 0] += 1['v2'][:, 0] += 1

    # Write back to file
Bookmark and Share


About Rick van Hattem

Rick van Hattem is a Dutch Internet entrepreneur and co-founder of

2 Responses to “Reading and writing binary STL files with Numpy”

  1. Sukhbinder | 2014-10-20 at 16:51:44 #

    Nice Rick!!! Makes the code more useful and thanks for putting it on pypi Wow why didn’t i think of it… Cheers!!


  1. Reading/writing 3D STL files with numpy-stl | Wolph - 2015-06-09

    […] a followup of my earlier article about reading and writing STL files with Numpy, I’ve created a library that can be used […]

Leave a Reply