Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an in-memory zip file with directories without touching the disk?

Tags:

python

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

like image 547
pthulin Avatar asked Aug 31 '10 14:08

pthulin


People also ask

How do I zip all folders?

Right-click on the file or folder.Select “Compressed (zipped) folder”. To place multiple files into a zip folder, select all of the files while hitting the Ctrl button. Then, right-click on one of the files, move your cursor over the “Send to” option and select “Compressed (zipped) folder”.

How do I create a zip folder without a new folder?

To select non-consecutive files or folders, hold down the Ctrl key as you select the individual files and/or folders. 2. Right-click on the file or folder (or group of files or folders), then point to Send to and select Compressed (zipped) folder. 3.

How do I zip a folder in shell script?

The easiest way to zip a folder on Linux is to use the “zip” command with the “-r” option and specify the file of your archive as well as the folders to be added to your zip file. You can also specify multiple folders if you want to have multiple directories compressed in your zip file.

How do I make an empty zip file?

1) Locate the place you want to create a ZIP File. Right-click on the blank space. Then click New > Compressed(zipped) Folder. 2) Now a new blank ZIP File is created, you can rename it and add the file or folder you want to compress into it by easy copy-paste.


2 Answers

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)
like image 178
pthulin Avatar answered Oct 01 '22 23:10

pthulin


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

like image 36
Katriel Avatar answered Oct 01 '22 23:10

Katriel