简体   繁体   English

如何从 zipfile 关闭 zip 文件?

[英]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.当我尝试解压文件并删除旧文件时,它说它仍在运行,所以我使用了关闭 function,但它没有关闭它。

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.在 Windows 操作系统上,与 Linux 不同,如果系统上有任何进程在该文件上打开了文件句柄,则无法删除该文件。

In this case, you write the file via handle fh and read it back via myzip .在这种情况下,您通过句柄fh写入文件并通过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? 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")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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