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

解压图片Zip文件夹后删除原文件触发PermissionError的原因及解决

Zip文件解压后无法删除的问题解决

问题详情

解压图片文件夹后尝试删除原Zip文件时触发权限错误,提示文件被其他进程占用。相关代码及报错信息如下:

相关代码

if item['mimeType'] == 'application/zip':
    print("Unzipping images into folder...")
    with zipfile.ZipFile(local_file_path, 'r') as zip_ref:
        zip_ref.extractall(local_directory) # Unzips the downloaded images into the specified folder
    zip_ref.close()
    os.remove(local_file_path) # remove the zip file after extraction

报错回溯

File "c:\Users\anton\Documents\python-scripts\download-image-folders-v1.py", line 133, in <module>
for image_folder_id in google_drive_image_folder_ids:
File "c:\Users\anton\Documents\python-scripts\download-image-folders-v1.py", line 126, in download_image_folders
zip_ref.close()
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:\\Users\\anton\\Pictures\\CURRENT IMAGE FOLDER\\9 Batches Part 1.zip'

问题分析与解决方法

这是Windows系统下非常常见的文件资源占用问题,核心问题出在代码逻辑上:

  • 你使用了with语句管理ZipFile对象,with块执行完成后会自动调用close()方法释放文件句柄,不需要手动执行zip_ref.close()。
  • 手动调用zip_ref.close()属于重复操作,反而可能导致文件资源未完全释放,触发删除时的权限错误。

最优解决方案

直接删除多余的zip_ref.close()代码,修改后的代码如下:

if item['mimeType'] == 'application/zip':
    print("Unzipping images into folder...")
    with zipfile.ZipFile(local_file_path, 'r') as zip_ref:
        zip_ref.extractall(local_directory) # Unzips the downloaded images into the specified folder
    os.remove(local_file_path) # remove the zip file after extraction

备选方案(若仍有偶发问题)

如果修改后偶尔还是出现文件占用问题,可以添加短暂延时,给系统足够时间释放文件资源:

import time

# ... 其他业务代码 ...

if item['mimeType'] == 'application/zip':
    print("Unzipping images into folder...")
    with zipfile.ZipFile(local_file_path, 'r') as zip_ref:
        zip_ref.extractall(local_directory)
    time.sleep(1) # 等待1秒确保文件资源释放
    os.remove(local_file_path)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 14:52:39