如何更新zip文件中的一个文件? [英] How to update one file inside zip file?

查看:50
本文介绍了如何更新zip文件中的一个文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个 zip 文件结构.

I have this zip file structure.

zipfile name = filename.zip

zipfile name = filename.zip

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

我只想更新 index.html.我试图更新 index.html,但随后它只包含 1.zip 文件中的 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.

这是我试过的代码:

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')

那么如何使用 Python 只更新 index.html 文件?

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

推荐答案

不支持更新 ZIP 中的文件.您需要重建一个没有该文件的新存档,然后添加更新的版本.

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)

请注意,您需要使用 Python 2.6 及更早版本的 contextlib,因为 ZipFile 也是仅自 2.7 以来的上下文管理器.

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.

这篇关于如何更新zip文件中的一个文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆