Name

writestr

Synopsis

                        z.writestr(zinfo,bytes)

zinfo must be a ZipInfo instance specifying at least filename and date_time. bytes is a string of bytes. writestr adds a member to archive z, using the metadata specified by zinfo and the data in bytes. z must be opened for 'w' or 'a‘. When you have data in memory and need to write the data to the ZIP file archive z, it’s simpler and faster to use z .writestr rather than z .write. The latter approach would require you to write the data to disk first, and later remove the useless disk file. The following example shows both approaches, each encapsulated into a function, polymorphic to each other:

import zipfile
def data_to_zip_direct(z, data, name):
    import time
    zinfo = zipfile.ZipInfo(name, time.localtime( )[:6])
    zinfo.compress_type = zipfile.ZIP_DEFLATED
    z.writestr(zinfo, data)
def data_to_zip_indirect(z, data, name):
    import os
    flob = open(name, 'wb')
    flob.write(data)
    flob.close( )
    z.write(name)
    os.unlink(name)
zz = zipfile.ZipFile('z.zip', 'w', zipfile.ZIP_DEFLATED)
data = 'four score\nand seven\nyears ago\n'
data_to_zip_direct(zz, data, 'direct.txt')
data_to_zip_indirect(zz, data, 'indirect.txt')
zz.close( )

Besides being faster and more concise, data_to_zip_direct is handier because, by working in memory, it doesn’t need to have the current working directory be writable, as data_to_zip_indirect does. Of course, method write also has its uses, but that’s mostly when you already have the data in a file on disk, and just want to add the ...

Get Python in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.