Unable To Remove Zipped File After Unzipping
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 though
Solution 1:
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'withopen(zipped_file, mode="r") as file:
zip_file = zipfile.ZipFile(file)
for member in zip_file.namelist():
filename = os.path.basename(member)
ifnot filename:
continue
source = zip_file.open(member)
os.remove(zipped_file)
Solution 2:
You are opening files inside the zip... which create a file lock on the whole zip file. close the inner file open first... via source.close() at the end of your loop
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)
ifnot filename:
continue
source = zip_file.open(member)
source.close()
os.remove(zipped_file)
Solution 3:
you can do also like this, which works pretty good:
import os, shutil, zipfile
fpath= 'C:/Users/dest_folder'path = os.getcwd()
for file inos.listdir(path):
if file.endswith(".zip"):
dirs = os.path.join(path, file)
ifos.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)
Solution 4:
Try to close the zipfile before removing.
Post a Comment for "Unable To Remove Zipped File After Unzipping"