2012-07-05 49 views
3

我想在壓縮文件中包含一個二進制文件,下面是代碼片段: 我首先將zip內容解壓縮到一個臨時位置,然後添加幾個文件並將其壓縮回一個新的檔案。在python中壓縮一個二進制文件

import zipfile 

def test(fileName, tempDir): 
    # unzip the file contents,may contain binary files 
    myZipFile=zipfile.ZipFile(fileName,'r') 
    for name in myZipFile.namelist(): 
     toFile = tempDir + '/' + name 
     fd = open(toFile, "w") 
     fd.write(myZipFile.read(name)) 
     fd.close() 
    myZipFile.close() 
    # code which post processes few of the files goes here 

    #zip it back 
    newZip = zipfile.ZipFile(fileName, mode='w') 
    try: 
     fileList = os.listdir(tempDir) 
     for name in fileList: 
      name = tempDir + '/' + name 
      newZip.write(name,os.path.basename(name)) 
     newZip.close() 
    except Exception: 
      print 'Exception occured while writing to PAR file: ' + fileName  

某些文件可能是二進制文件。該荏苒代碼工作正常,但是當我嘗試使用Linux的解壓縮或Python的壓縮模塊,將其解壓,我得到下面的錯誤:

zipfile corrupt. (please check that you have transferred or created the zipfile in the appropriate BINARY mode and that you have compiled UnZip properly)

和我使用Python 2.3

什麼錯嗎?

+0

請後'newZip'並更正intendation'爲'並且請添加'import zipfile' –

+0

對我來說看起來非常合適用Python3 +進行了最小的變化和工作測試 –

+0

也可以在Python 2.7中使用它可能是2.3中的錯誤或者其他錯誤 - 你是否試圖打開它與不同的zip程序? – Tisho

回答

2

嗯不知道它是否是Python 2.3中的一個bug。當前的工作環境不允許我升級到更高版本的Python :-(:-(:-(

以下解決方法的工作:

import zipfile 

def test(fileName, tempDir): 
    # unzip the file contents,may contain binary files 
    myZipFile=zipfile.ZipFile(fileName,'r') 
    for name in myZipFile.namelist(): 
     toFile = tempDir + '/' + name 

     # check if the file is a binary file 
     #if binary file, open it in "wb" mode 
      fd = open(toFile, "wb") 
     #else open in just "w" mode 
      fd = open(toFile, "w") 

     fd.write(myZipFile.read(name)) 
     fd.close() 
    myZipFile.close() 
    # code which post processes few of the files goes here 

    #zip it back 
    newZip = zipfile.ZipFile(fileName, mode='w') 
    try: 
     fileList = os.listdir(tempDir) 
     for name in fileList: 
      name = tempDir + '/' + name 
      newZip.write(name,os.path.basename(name)) 
     newZip.close() 
    except Exception: 
      print 'Exception occured while writing to PAR file: ' + fileName  
2

您可能想要升級,因爲Python 2.3確實過時了。 2.7.3是來自2.x版本和3.2.3最新Python版本的最新版本。

docs.python.org

| extractall(self, path=None, members=None, pwd=None) 
|  Extract all members from the archive to the current working 
|  directory. `path' specifies a different directory to extract to. 
|  `members' is optional and must be a subset of the list returned 
|  by namelist(). 

(新版本2.6)

Zip a folder and its content看看。您可能也有興趣distutlis.archive_util