Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

zipfile

I have this zip file structure.

zipfile name = filename.zip

filename>    images>
             style.css
             default.js
             index.html

I want to update just index.html. I tried to update index.html, but then it contains only index.html file in 1.zip file and other files are removed.

This is the code which I tried:

import zipfile

msg = 'This data did not exist in a file before being added to the ZIP file'
zf = zipfile.ZipFile('1.zip', 
                     mode='w',
                     )
try:
    zf.writestr('index.html', msg)
finally:
    zf.close()
    
print zf.read('index.html')

So how can I update only index.html file using Python?

like image 262
user3932031 Avatar asked Sep 09 '14 07:09

user3932031


2 Answers

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.

like image 122
sebdelsol Avatar answered Oct 07 '22 02:10

sebdelsol


It is not possible to update an existing file. You will need to read the file you want to edit and create a new archive including the file that you edited and the other files that were originally present in the original archive.

Below are some of the questions that might help.

Delete file from zipfile with the ZipFile Module

overwriting file in ziparchive

How do I delete or replace a file in a zip archive

like image 26
g4ur4v Avatar answered Oct 07 '22 00:10

g4ur4v