1

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")
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
  • Hey, the same code i tried one of my ZIP , it is working find without errors – Tamil Selvan Nov 25 '21 at 20:10
  • Are you running on Windows? This is probably OS specific behaviour. – joanis Nov 25 '21 at 20:19
  • @joanis Yes I am, but I am planning on also running on linux – EnderPrince Nov 25 '21 at 20:20
  • I suspect this code will work as is on Linux. On Windows, you cannot delete a file that is open by any process, while on Linux there is no such restriction. Let's tag this question Windows since that's where the problem exists. – joanis Nov 25 '21 at 20:21
  • Hmm, just tried to reproduce on my Windows machine, and it works without any error, the file gets deleted. Is there any chance you have some other process holding that zip file open on your machine? Windows is super picky about that, no app can have a handle on a file you're trying to delete. – joanis Nov 25 '21 at 20:28
  • @joanis I added the only part that calls it before then, but I dont think its the problem, its using google api, but I think you can answer it without knowledge of it – EnderPrince Nov 25 '21 at 20:32
  • 1
    I don't see a call to close `fh`, I bet that's the problem. – joanis Nov 25 '21 at 20:58
  • 1
    @joanis that was it, I was trying to close status for some reason, I never thought of closing fh, tysm – EnderPrince Nov 25 '21 at 21:12

2 Answers2

2

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

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.

joanis
  • 10,635
  • 14
  • 30
  • 40