EnderPrince
EnderPrince

Reputation: 37

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

Upvotes: 1

Views: 3184

Answers (2)

joanis
joanis

Reputation: 12229

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.

Upvotes: 2

seldomspeechless
seldomspeechless

Reputation: 174

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

Upvotes: 2

Related Questions