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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | 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) zip.close() def read(self): self.inMemoryOutputFile.seek(0) return self.inMemoryOutputFile.getvalue() def writetofile(self, filename): open('out.zip', 'wb').write(self.read()) |
Save as “inmemoryzip.py” 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.