19

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

pthulin
  • 4,001
  • 3
  • 21
  • 23

2 Answers2

33

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
  • 4,001
  • 3
  • 21
  • 23
1

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

Community
  • 1
  • 1
Katriel
  • 120,462
  • 19
  • 136
  • 170