How to update one file inside zip file? [duplicate]

Updating a file in a ZIP is not supported. You need to rebuild a new archive without the file, then add the updated version.

import os
import zipfile
import tempfile

def updateZip(zipname, filename, data):
    # generate a temp file
    tmpfd, tmpname = tempfile.mkstemp(dir=os.path.dirname(zipname))
    os.close(tmpfd)

    # create a temp copy of the archive without filename            
    with zipfile.ZipFile(zipname, 'r') as zin:
        with zipfile.ZipFile(tmpname, 'w') as zout:
            zout.comment = zin.comment # preserve the comment
            for item in zin.infolist():
                if item.filename != filename:
                    zout.writestr(item, zin.read(item.filename))

    # replace with the temp archive
    os.remove(zipname)
    os.rename(tmpname, zipname)

    # now add filename with its new data
    with zipfile.ZipFile(zipname, mode="a", compression=zipfile.ZIP_DEFLATED) as zf:
        zf.writestr(filename, data)

msg = 'This data did not exist in a file before being added to the ZIP file'
updateZip('1.zip', 'index.html', msg)

Note that you need contextlib with Python 2.6 and earlier, since ZipFile is also a context manager only since 2.7.

You might want to check if your file actually exists in the archive to avoid an useless archive rebuild.

Leave a Comment