Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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)

The error returned is:

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

I've tried:

  • 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
like image 764
Stagg Avatar asked Jan 06 '23 18:01

Stagg


2 Answers

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)
like image 54
James Kent Avatar answered Jan 14 '23 00:01

James Kent


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)
        if not filename:
            continue
        source = zip_file.open(member)
    source.close()

os.remove(zipped_file)
like image 27
James Avatar answered Jan 14 '23 02:01

James