tags:

views:

76

answers:

3

In a python web application, I'm packaging up some stuff in a zip-file. I want to do this completely on the fly, in memory, without touching the disk. This goes fine using ZipFile.writestr as long as I'm creating a flat directory structure, but how do I create directories inside the zip?

I'm using python2.4.

http://docs.python.org/library/zipfile.html

+1  A: 

Take a look at this answer: http://stackoverflow.com/questions/458436/adding-folders-to-a-zip-file-using-python/459419#459419

It basically suggest using the second argument of zipfile.write to add a file in a particular path within the zip file.

Jacobo de Vera
+1  A: 

Use a StringIO. It is apparently OK to use them for zipfiles.

katrielalex
We do this also. Works very nicely.
S.Lott
+1  A: 

What 'theomega' said in the comment to my original post, adding a '/' in the filename does the trick. Thanks!

from zipfile import ZipFile
from StringIO import StringIO

inMemoryOutputFile = StringIO()

zipFile = ZipFile(inMemoryOutputFile, 'w') 
zipFile.writestr('OEBPS/content.xhtml', 'hello world')
zipFile.close()

inMemoryOutputFile.seek(0)
pthulin