【问题标题】:python - file duplicated when updating zip archivepython - 更新zip存档时文件重复
【发布时间】:2018-03-12 11:44:10
【问题描述】:

我正在尝试更新 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))

当我这样调用这个函数时: 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)

当我用 WinZip 打开文件时,我可以看到 vbaProject.bin 是重复的。任何想法为什么以及如何纠正这种行为以复制 zip 中的所有文件除了来自 xl\vbaProject.bin

【问题讨论】:

    标签: python excel zip zipfile


    【解决方案1】:

    您传递给updateZip2()file 是:

    r'xl\vbaProject.bin'
    

    但存储在 ZIP 中的文件格式为:

    r'xl/vbaProject.bin'
    

    因此,如果您在通话中将 \ 更改为 /,它应该可以工作:

    updateZip2('Book1.xlsm', r'xl/vbaProject.bin', target2)
    

    或者,您可以将相等性测试更新为:

    if os.path.normpath(item.filename) != os.path.normpath(file):
    

    【讨论】:

      猜你喜欢
      • 2011-06-15
      • 2013-03-01
      • 2022-01-25
      • 2021-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-25
      • 1970-01-01
      相关资源
      最近更新 更多