如何使用python更新zip文件中的一个文件

use*_*031 9 python zipfile

我有这个zip文件结构.

zipfile name = filename.zip

filename>    images>
             style.css
             default.js
             index.html
Run Code Online (Sandbox Code Playgroud)

我想只更新index.html.我试图更新index.html,但它只包含1.zip文件中的index.html文件,其他文件被重新驱动.

这是我试过的代码:

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')
Run Code Online (Sandbox Code Playgroud)

那么如何才能使用Python更新index.html文件呢?

seb*_*sol 22

不支持以ZIP格式更新文件.您需要在没有该文件的情况下重建新存档,然后添加更新的版本.

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)
Run Code Online (Sandbox Code Playgroud)

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

您可能想要检查存档中是否存在实际存在的文件,以避免无用的存档重建.

  • 只是想说谢谢,这个脚本对我帮助很大! (2认同)

g4u*_*r4v 5

无法更新现有文件。您将需要读取要编辑的文件并创建一个新的存档,其中包括您编辑的文件以及原始存档中最初存在的其他文件。

以下是一些可能有帮助的问题。

使用 ZipFile 模块从 zipfile 中删除文件

覆盖 ziparchive 中的文件

如何删除或替换 zip 存档中的文件