You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ZipFile.extractall调用后zip被清空但文件未写入指定路径问题求解

故障根因
  • 核心逻辑顺序错误:ZipFile(backupZip, 'w')的w模式会在执行时立即清空原有压缩包内容,无论后续是否成功写入文件。原有代码优先执行写模式打开压缩包的逻辑,只要任意一个待备份文件不存在触发异常时,原备份压缩包已经被清空,自然无法提取出有效文件。
  • 路径转义隐患:Windows路径直接写在普通字符串中时,反斜杠可能被识别为转义字符,导致文件提取路径不符合预期。
修复方案

调整逻辑执行顺序,先校验待备份文件是否全部存在,确认无误后再执行备份逻辑,避免无意义清空原有备份压缩包。同时修复路径转义问题。

修正后代码

from zipfile import ZipFile
import os

files = ['Combine1.docm', 'Combine2.docm', 'Combine3.docm',
        'Combine4.docm', 'Combine5.docm', 'FinalMaster.docm',
        'FinalMasterBeltDrier.docm', 'FinalMasterExport.docm']

backupZip = 'WorkaroundBackup.zip'

def ZipSave(files, backupZip):             
    # 校验所有待备份文件是否存在
    all_files_exist = all(os.path.exists(file) for file in files)
    if all_files_exist:
        # 所有文件存在时再执行备份逻辑,避免提前清空压缩包
        with ZipFile(backupZip, 'w') as zipWrite:
            for file in files:
                zipWrite.write(file, compress_type=None)
        print('Files backed up to %s.' % backupZip)
    else:
        # 文件缺失时走恢复逻辑,路径前加r标识为原始字符串避免转义问题
        with ZipFile(backupZip, 'r') as zipRead:
            zipRead.extractall(path = r'F:\DW Master\Template Docs Workaround')
        print('Files not found; restoring from %s.' % backupZip)

ZipSave(files, backupZip)

内容的提问来源于stack exchange,提问作者MaccyF

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 19:36:03