python – 解压缩后无法删除压缩文件

我正在尝试在解压缩
Windows上的内容后删除压缩文件.内容可以存储在zip中的文件夹结构中.我正在使用with语句,并认为这将关闭类文件对象(源var)和zip文件.我删除了与保存源文件相关的代码行.

import zipfile
import os

zipped_file = r'D:\test.zip'

with zipfile.ZipFile(zipped_file) as zip_file:
    for member in zip_file.namelist():
        filename = os.path.basename(member)
        if not filename:
            continue
        source = zip_file.open(member)

os.remove(zipped_file)

返回的错误是:

WindowsError: [Error 32] The process cannot access the file because it is being used by another process: 'D:\\test.zip'

我试过了:

>在os.remove行上循环,以防出现轻微的时间问题
>明确使用close而不是with with statment
>尝试使用本地C驱动器并映射D驱动器

最佳答案 而不是将字符串传递给ZipFile构造函数,您可以传递一个像object这样的文件:

import zipfile
import os

zipped_file = r'D:\test.zip'

with open(zipped_file, mode="r") as file:
    zip_file = zipfile.ZipFile(file)
    for member in zip_file.namelist():
        filename = os.path.basename(member)
        if not filename:
            continue
        source = zip_file.open(member)

os.remove(zipped_file)
点赞