我正在尝试更新 zip 存档中的文件并将其另存为新存档。我使用的 zip 存档是一个 Excel.xlsm
文件,我需要修改的文件位于子文件夹中:xl/vbaProject.bin
。我编写了一个函数(通过修改此处发布的函数:How to update one file inside zip file using python)。
def updateZip2(zip_name, file, data):
# generate a temp file
tmp = os.path.splitext(ntpath.basename(zip_name))[0] + '_new.xlsm'
tmpname = str(pathlib.Path(zip_name).parent.joinpath(tmp))
print(tmpname)
with zipfile.ZipFile(zip_name, '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.find(file) == -1:
zout.writestr(item, zin.read(item.filename))
Run Code Online (Sandbox Code Playgroud)
当我像这样调用这个函数时:
按预期创建了updateZip2('Book1.xlsm', r'xl\vbaProject.bin', target2)
一个新函数Book1_new.xlsm
,但我收到警告:
C:\ProgramData\Anaconda3\lib\zipfile.py:1355: UserWarning: Duplicate name: 'xl/vbaProject.bin'
return self._open_to_write(zinfo, force_zip64=force_zip64)
Run Code Online (Sandbox Code Playgroud)
当我用 WinZip 打开该文件时,我可以看到 vbaProject.bin 是重复的。任何想法为什么以及如何纠正此行为以复制 zip 中的所有文件(除了来自 xl\vbaProject.bin
您要file
传递给的updateZip2()
是:
r'xl\vbaProject.bin'
Run Code Online (Sandbox Code Playgroud)
但 ZIP 中存储的文件格式为:
r'xl/vbaProject.bin'
Run Code Online (Sandbox Code Playgroud)
因此,如果您在通话中\
更改为:/
updateZip2('Book1.xlsm', r'xl/vbaProject.bin', target2)
Run Code Online (Sandbox Code Playgroud)
或者,您可以将相等测试更新为:
if os.path.normpath(item.filename) != os.path.normpath(file):
Run Code Online (Sandbox Code Playgroud)