gpt4 book ai didi

Python zipfile 不释放 zip 文件

转载 作者:可可西里 更新时间:2023-11-01 09:37:39 26 4
gpt4 key购买 nike

我正在尝试使用 zipfile Windows 8.1 和 python 2.7.9 上的库。

我只想在 zipfile.open() 之后删除 library.zip,但 os.remove() 抛出“WindowsError [Error 32]”,而且 zipfile 似乎没有从 block 中释放 zip 文件。

WindowsError 32 表示“该进程无法访问该文件,因为它正被另一个进程使用。”

那么,我该如何删除这个 library.zip 文件呢?

代码:

import os
import zipfile as z

dirs = os.listdir('build/')
bSystemStr = dirs[0]

print("[-] Merging library.zip...")
with z.ZipFile('build/' + bSystemStr + '/library.zip', 'a') as z1:
with z.ZipFile('build_temp/' + bSystemStr + '/library.zip', 'r') as z2:
for t in ((n, z2.open(n)) for n in z2.namelist()):
try:
z1.writestr(t[0], t[1].read())
except:
pass

print("[-] Cleaning temporary files...")
os.remove('build_temp/' + bSystemStr + '/library.zip')

错误:

[-]Merging library.zip...
...
build.py:74: UserWarning: Duplicate name: 'xml/sax/_exceptions.pyc'
z1.writestr(t[0], t[1].read())
build.py:74: UserWarning: Duplicate name: 'xml/sax/expatreader.pyc'
z1.writestr(t[0], t[1].read())
build.py:74: UserWarning: Duplicate name: 'xml/sax/handler.pyc'
z1.writestr(t[0], t[1].read())
build.py:74: UserWarning: Duplicate name: 'xml/sax/saxutils.pyc'
z1.writestr(t[0], t[1].read())
build.py:74: UserWarning: Duplicate name: 'xml/sax/xmlreader.pyc'
z1.writestr(t[0], t[1].read())
build.py:74: UserWarning: Duplicate name: 'xmllib.pyc'
z1.writestr(t[0], t[1].read())
build.py:74: UserWarning: Duplicate name: 'xmlrpclib.pyc'
z1.writestr(t[0], t[1].read())
build.py:74: UserWarning: Duplicate name: 'zipfile.pyc'
z1.writestr(t[0], t[1].read())
[-] Cleaning temporary files...
Traceback (most recent call last):
File "build.py", line 79, in <module>
os.remove('build_temp/' + bSystemStr + '/library.zip')
WindowsError: [Error 32] : 'build_temp/exe.win32-2.7/library.zip'

最佳答案

我认为您必须在删除存档或退出程序之前关闭存档,如 python 文档中所述 https://docs.python.org/2/library/zipfile.html#zipfile.ZipFile.close

因此在删除存档之前运行 z1.close()z2.close()

您的代码必须如下所示:

import os
import zipfile as z

dirs = os.listdir('build/')
bSystemStr = dirs[0]

print("[-] Merging library.zip...")
with z.ZipFile('build/' + bSystemStr + '/library.zip', 'a') as z1:
with z.ZipFile('build_temp/' + bSystemStr + '/library.zip', 'r') as z2:
for t in ((n, z2.open(n)) for n in z2.namelist()):
try:
z1.writestr(t[0], t[1].read())
except:
pass

z2.close()

z1.close()


print("[-] Cleaning temporary files...")
os.remove('build_temp/' + bSystemStr + '/library.zip')

如果我错了,请纠正我。

关于Python zipfile 不释放 zip 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28350458/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com