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'? Commented Aug 31, 2010 at 15:01

2 Answers 2

35

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)
Sign up to request clarification or add additional context in comments.

3 Comments

Note that if you're using python 3 then you'll want to use BytesIO.
And if you just want to have folders without files, leave a / at the end.
Important is that inMemoryOutputFile is actually sent and not the zipFile object.
1

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

2 Comments

We do this also. Works very nicely.
@AnotherParker If you have a more modern solution, please post and I will upvote

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.