Home > Net >  How to close zip file, from zipfile?
How to close zip file, from zipfile?

Time:11-26

When I try to unzip a file, and delete the old file, it says that its 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 dont think its 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")

CodePudding user response:

Try using with. That way you don't have to close at all. :)

with ZipFile(f'{onlineLatest}.zip', 'r') as zf:
    zf.extractall(f'{onlineLatest}')

CodePudding user response:

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.

  • Related