4

バイナリ ファイルを 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's zip module を使用して解凍しようとすると、次のエラーが発生します。

zip ファイルが破損しています。(適切なバイナリ モードで zip ファイルを転送または作成したこと、および UnZip を適切にコンパイルしたことを確認してください)

そしてpython 2.3を使用しています

ここで何がうまくいかないのですか?

4

2 に答える 2

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にも興味があるかもしれません。

于 2012-07-05T06:58:17.473 に答える
2

うーん、それがpython 2.3のバグかどうかはわかりません。現在の作業環境では、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    
于 2012-07-05T07:20:57.990 に答える