Search code examples
pythonwindowszippython-zipfile

How to close zip file, from zipfile?


When I try to unzip a file, and delete the old file, it says that it's still running, so I used the close function, but it doesn't close it.

Here is my code:

import zipfile
import os

onlineLatest = "testFile"
myzip = zipfile.ZipFile(f'{onlineLatest}.zip', 'r')
myzip.extractall(f'{onlineLatest}')
myzip.close()
os.remove(f"{onlineLatest}.zip")

And I get this error:

PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'Version 0.1.2.zip'

Anyone know how to fix this?

Only other part that runs it before, but don't think it's the problem:

request = service.files().get_media(fileId=onlineVersionID)
fh = io.FileIO(f'{onlineLatest}.zip', mode='wb')
downloader = MediaIoBaseDownload(fh, request)
done = False
while done is False:
    status, done = downloader.next_chunk()
    print("Download %d%%." % int(status.progress() * 100))

myzip = zipfile.ZipFile(f'{onlineLatest}.zip', 'r')
myzip.extractall(f'{onlineLatest}')
myzip.close()
os.remove(f"{onlineLatest}.zip")

Solution

  • Wrapping up the discussion in the comments into an answer:

    On the Windows operating system, unlike in Linux, a file cannot be deleted if there is any process on the system with a file handle open on that file.

    In this case, you write the file via handle fh and read it back via myzip. Before you can delete it, you have to close both file handles.