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)

相关文章

功能概要:(目前已实现功能)公共展示部分:1.网站首页展示...
大体上把Python中的数据类型分为如下几类: Number(数字) ...
开发之前第一步,就是构造整个的项目结构。这就好比作一幅画...
源码编译方式安装Apache首先下载Apache源码压缩包,地址为ht...
前面说完了此项目的创建及数据模型设计的过程。如果未看过,...
python中常用的写爬虫的库有urllib2、requests,对于大多数比...