我试图在解压缩Windows上的内容后删除压缩文件。内容可以存储在zip中的文件夹结构中。我使用with
语句并认为这会关闭类似文件的对象(source
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
行,以防出现轻微的时间问题with
statment 答案 0 :(得分:6)
不是将字符串传递给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 :(得分:2)
您正在打开zip中的文件...这会在整个zip文件上创建文件锁。关闭内部文件首先打开...通过循环结束时的source.close()
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)
source.close()
os.remove(zipped_file)
答案 2 :(得分:0)
您也可以这样做,效果很好:
import os, shutil, zipfile
fpath= 'C:/Users/dest_folder'
path = os.getcwd()
for file in os.listdir(path):
if file.endswith(".zip"):
dirs = os.path.join(path, file)
if os.path.exists(fpath):
shutil.rmtree(fpath)
_ = os.mkdir(fpath)
with open(dirs, 'rb') as fileobj:
z = zipfile.ZipFile(fileobj)
z.extractall(fpath)
z.close()
os.remove(dirs)
答案 3 :(得分:-1)
在删除之前尝试close zipfile。