Search code examples
pythoniozip

Python: Want to write zipfile.ZipFile object to disk as "foo.zip"


It feels like I'm missing something obvious here.

I have a zipfile.ZipFile object, which was created by writing files into it using io.BytesIO() called buffer as follows:

with zipfile.ZipFile(buffer, "a") as zip:
    # write some things into the zip using zip.write()

then I returned zip, so I have a zipfile.ZipFile object.

I want to write this object to disk as a zipped file, and I don't know how.

zip.write('foo.zip')

would write things into the object, and

with open('foo.zip', 'wb') as f:
    f.write(zip)

doesn't work because zip isn't a bytes object.

with open('foo.zip', 'wb') as f:
    f.write(zip.read())

doesn't work because it's expecting a "name", which I presume is the name of one of the files saved within zip. I would have assumed there was just some simple way to do this, e.g. zip.to_zip("foo.zip")?

UPDATE: Because zip was originally written into the buffer, I tried changing zip.filename to "test.zip" which does write the zip to disk. However, the contents of zip aren't there. This could be a different issue, but I'm unsure.


Solution

  • You need to write contents of buffer, not zip, since everything you write using zip.write(filename) is being put into the buffer, as you passed it as a first argument of zipfile.ZipFile() call.

    I would also suggest to avoid using zip as a variable name since it shadows built-in zip(*iterables) function.

    Here is an example:

    buffer = io.BytesIO()
    
    with zipfile.ZipFile(buffer, "a") as zip_file:
        zip_file.write('data.txt')
    
    with open('foo.zip', 'wb') as f:
        f.write(buffer.getvalue())