解压后无法删除压缩文件 [英] Unable to remove zipped file after unzipping
本文介绍了解压后无法删除压缩文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 Windows 上解压缩内容后,我试图删除压缩文件.内容可以存储在 zip 的文件夹结构中.我正在使用 with
语句,并认为这会关闭类文件对象 (source
var) 和 zip 文件.我删除了与保存源文件相关的代码行.
I'm attempting to remove a zipped file after unzipping the contents on windows. The contents can be stored in a folder structure in the zip. I'm using the with
statement and thought this would close the file-like object (source
var) and zip file. I've removed lines of code relating to saving the source file.
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
语句 - 尝试在本地 C 盘和映射 D 盘
- looping over the
os.remove
line in case it's a slight timing issue - Using close explicitly instead of the
with
statment - Attempted on local C drive and mapped D Drive
推荐答案
不是将字符串传递给 ZipFile
构造函数,您可以将它传递给类似对象的文件:
instead of passing in a string to the ZipFile
constructor, you can pass it a file like 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)
这篇关于解压后无法删除压缩文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文