alphanumeric
alphanumeric

Reputation: 19379

How to save ZIP in-memory-file-object in Python

With zip file object initiated as fileobj:

import io, zipfile, time 

filepath = '/temp/my_file.bin'

fileobj = io.BytesIO()

with zipfile.ZipFile(fileobj, 'w') as zf:
    data = zipfile.ZipInfo(filepath)
    data.date_time = time.localtime(time.time())[:6]
    data.compress_type = zipfile.ZIP_DEFLATED
    with open(filepath, 'rb') as fd:
        zf.writestr(data, fd.read())
fileobj.seek(0)

I want to save the file to a local disk. How to save the fileobj as a local zip file my_zip.zip?

Upvotes: 1

Views: 2107

Answers (1)

call-in-co
call-in-co

Reputation: 291

I think zipfile.ZipInfo.from_file will help you here:

import time, zipfile

filepath = '/temp/my_file.bin'
local_path_to_write = 'my_zip.zip'
with zipfile.ZipFile(local_path_to_write, 'w', compresslevel=zipfile.ZIP_DEFLATED) as zf:
    zf.ZipInfo = zipfile.ZipInfo.from_file(filepath)
    # if you really need to edit the time attribute:
    # zf.ZipInfo.date_time = localtime()[:6]
    zf.write(filepath)

Upvotes: 1

Related Questions