How to update one file inside zip file using python [duplicate]

痴心易碎 提交于 2019-11-27 20:35:21

问题


This question already has an answer here:

  • overwriting file in ziparchive 2 answers

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 remobved.

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?


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/25738523/how-to-update-one-file-inside-zip-file-using-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!