Gravatar of Jeroen Jeroen Pelgrims

Python in-memory zip file

Posted on in python, software-development

I needed this for something where I wanted to send the visitor of a website a bunch of files he selected at once. An easy way to do this would be to add the files to a zip file and then send that zip file to the user. Unfortunately Python doesn't have an in-memory zip file library, you can only interact with zip files on disk.

After a bit of googling around I came to this StackOverflow answer. That worked like a charm, and here is my more reusable version:

from zipfile import ZipFile
from StringIO import StringIO

class InMemoryZipFile(object):
    def __init__(self):
        self.inMemoryOutputFile = StringIO()

    def write(self, inzipfilename, data):
        zip = ZipFile(self.inMemoryOutputFile, 'a')
        zip.writestr(inzipfilename, data)

    def read(self):
        return self.inMemoryOutputFile.getvalue()

    def writetofile(self, filename):
        open('', 'wb').write(

Save as and import it as inmemoryzip. This is quite limited compared to the standard ZipFile class, but this gets the job done for what I needed it.

This post is written by Jeroen Pelgrims, an independent software developer who runs

Hire Jeroen