Skip to content

Instantly share code, notes, and snippets.

@bamthomas
Last active December 29, 2015 00:49
Show Gist options
  • Save bamthomas/7588291 to your computer and use it in GitHub Desktop.
Save bamthomas/7588291 to your computer and use it in GitHub Desktop.
in memory zip with python
from zipfile import ZipFile
def append_file(memory_stream, file_name, file_content):
with ZipFile(memory_stream, 'a') as zf:
zf.writestr(file_name, file_content)
from io import BytesIO
import unittest
from zipfile import ZipFile
import myzip
class TestZip(unittest.TestCase):
def test_zip(self):
memory_stream = BytesIO()
myzip.append_file(memory_stream, 'filename1', 'content of file')
myzip.append_file(memory_stream, 'filename2', 'content of another file')
with ZipFile(memory_stream) as zf:
self.assertEqual(2, len(zf.filelist))
self.assertEqual('filename1', zf.filelist[0].filename)
self.assertEqual('filename2', zf.filelist[1].filename)
self.assertEqual('content of file', zf.read('filename1'))
self.assertEqual('content of another file', zf.read('filename2'))
@bamthomas
Copy link
Author

And this doesn't work :

def create_zip(memory_stream):
    with ZipFile(memory_stream, 'a') as zf:
         zf.writestr('filename1', 'content of file')
         zf.writestr('filename2', 'content of file2')
         return zf

zip = create_zip(memory_stream)
# then do stuff with zip

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment