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

不支持更新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以来也只是一个上下文管理器.

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值