【问题标题】:How to update one file inside zip file? [duplicate]如何更新zip文件中的一个文件? [复制]
【发布时间】:2014-11-02 12:21:15
【问题描述】:

我有这个 zip 文件结构。

压缩文件名 = filename.zip

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

我只想更新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')

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

【问题讨论】:

  • 到目前为止你尝试过什么?向我们展示您的代码并描述哪些功能有效,哪些无效。

标签: python zipfile


【解决方案1】:

不支持更新 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)

请注意,您需要使用 Python 2.6 及更早版本的 contextlib,因为 ZipFile 从 2.7 开始也是上下文管理器。

您可能需要检查您的文件是否确实存在于存档中以避免无用的存档重建。

【讨论】:

  • 只是想说声谢谢,这个脚本对我帮助很大!
  • 我对临时文件的管理略有不同:首先,from tempfile import NamedTemporaryFile 然后使用临时文件,我只需将其余函数放入 with NamedTemporaryFile() as tmp_file: 并获取名称:@987654324 @。最后,不是os.rename(...),而是shutil.copyfile(tmpname, filename)。临时文件最终由上下文管理器处理和关闭。
【解决方案2】:

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

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

Delete file from zipfile with the ZipFile Module

overwriting file in ziparchive

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

【讨论】:

    猜你喜欢
    • 2011-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-08
    • 1970-01-01
    • 1970-01-01
    • 2021-04-29
    相关资源
    最近更新 更多