簡體   English   中英

Python zipfile不會發布zip文件

[英]Python zipfile dosen't release zip file

我正在嘗試在Windows 8.1和python 2.7.9上使用zipfile庫。

我只是想在zipfile.open()之后刪除library.zip,但os.remove()拋出“WindowsError [錯誤32]”並且似乎zipfile不會釋放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')

如果我錯了,請糾正我。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM