Nes*_*wit 5 python windows python-2.7 windows-8.1 python-zipfile
我正在尝试在 Windows 8.1 和 python 2.7.9 上使用zipfile库。
我只想在 zipfile.open() 之后删除library.zip,但 os.remove() 会抛出“WindowsError [Error 32]”,并且 zipfile 似乎不会将 zip 文件从 with 块中释放出来。
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')
Run Code Online (Sandbox Code Playgroud)
错误:
[-]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'
Run Code Online (Sandbox Code Playgroud)
小智 2
我认为您必须在删除存档或退出程序之前关闭存档,如 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')
Run Code Online (Sandbox Code Playgroud)
如果我错了,请纠正我。