简体   繁体   中英

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

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

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.

What was the solution that needs to be written on the code for windows? I am getting same error though I have closes the desired files

import zipfile
import os

srcfile = 'C:/Users/x.zip'
dstfile = 'C:/Users/x_out.zip'

inzip = zipfile.ZipFile(srcfile, 'r')
outzip = zipfile.ZipFile(dstfile, "w")

for inzipinfo in inzip.infolist():

    print(inzipinfo)
    
    # Read input file
    infile = inzip.open(inzipinfo)

    if inzipinfo.filename == "x.tds":

        content = infile.read()
        #print(content)
        
        new_content = str(content, 'utf-8').replace("abc", "xyz")
        
        outzip.writestr(inzipinfo.filename, new_content)
        
    else:  # Other file, dont want to modify => just copy it
        content = infile.read()
        outzip.writestr(inzipinfo.filename, content)
        

inzip.close()
outzip.close() 

thisFile = 'C:/Users/x.zip'
base = os.path.splitext(thisFile)[0]
os.rename(thisFile, base + ".tdsx")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM