我有这个功能,可以工作并替换给定文件中的内容.

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)

如果我按如下所示调用该函数两次,则文件中的文本为"Second Note".

updateZip('acor_en-US.dat', 'DocumentList.xml', 'first note')

updateZip('acor_en-US.dat', 'DocumentList.xml', 'second note')

但我需要那个档案里有and个"第一个音符"和"第二个音符". 换句话说,我不能附加一个压缩文件.

推荐答案

在重写文件之前,您需要从文件中读取数据:

import io
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)

    # read data from file
    with zipfile.ZipFile(zipname) as zf:
        with io.TextIOWrapper(zf.open(filename), encoding='utf-8') as f:
            data = f.read() + data

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


updateZip('acor_en-US.dat', 'DocumentList.xml', 'first note')
updateZip('acor_en-US.dat', 'DocumentList.xml', 'second note')

DocumentList.xml条内容:

first notesecond note

Python相关问答推荐

跳过包含某些键的字典

在IIS中运行的FastAPI-获取权限错误:[Win错误10013]试图以其访问权限禁止的方式访问插槽

在Python中,如何初始化集合列表脚本的输出

在Python中是否可以输入使用任意大小参数列表的第一个元素的函数

单击cookie按钮,但结果不一致

如何修复fpdf中的线路出血

无法导入已安装的模块

将numpy矩阵映射到字符串矩阵

Python中的函数中是否有充分的理由接受float而不接受int?

如何在Deliveryter笔记本中从同步上下文正确地安排和等待Delivercio代码中的结果?

点到面的Y距离

根据另一列中的nan重置值后重新加权Pandas列

Python json.转储包含一些UTF-8字符的二元组,要么失败,要么转换它们.我希望编码字符按原样保留

按顺序合并2个词典列表

用合并列替换现有列并重命名

NP.round解算数据后NP.unique

使用setuptools pyproject.toml和自定义目录树构建PyPi包

如何在python polars中停止otherate(),当使用when()表达式时?

如何在图中标记平均点?

在Python中使用yaml渲染(多行字符串)