我有这个功能,可以工作并替换给定文件中的内容.
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个"第一个音符"和"第二个音符". 换句话说,我不能附加一个压缩文件.