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

1
  • 6
    Have you tried simply setting the filename of a file to add to 'directory/filename.ext'?
    – theomega
    Aug 31, 2010 at 15:01

2 Answers 2

34

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)
3
  • 8
    Note that if you're using python 3 then you'll want to use BytesIO.
    – Panda
    Jun 11, 2015 at 15:19
  • And if you just want to have folders without files, leave a / at the end. Jan 26, 2018 at 9:41
  • 1
    Important is that inMemoryOutputFile is actually sent and not the zipFile object.
    – Quinten C
    Mar 29, 2020 at 3:52
1

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

2
  • We do this also. Works very nicely.
    – S.Lott
    Aug 31, 2010 at 15:47
  • 1
    @AnotherParker If you have a more modern solution, please post and I will upvote
    – Gillespie
    Oct 17, 2017 at 18:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.