在Python中压缩二进制文件

2skhul33  于 2023-03-28  发布在  Python
关注(0)|答案(2)|浏览(201)

我试图在zip文件中包含一个二进制文件,下面是代码片段:我首先将zip内容解压缩到一个临时位置,然后再添加几个文件,并将其压缩回一个新的存档。

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的unzip或python的zip模块解压缩它时,我得到以下错误:
zipfile corrupt.(请检查您是否以适当的BINARY模式传输或创建了zipfile,并且您是否正确编译了UnZip)
我用的是python2.3
出什么事了?

eeq64g8w

eeq64g8w1#

你可能需要升级,因为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().

(New版本2.6)
看一下Zip a folder and its content
您可能还对distutlis.archive_util感兴趣。

yvgpqqbh

yvgpqqbh2#

嗯,不确定这是不是python2.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

相关问题