我想在壓縮文件中包含一個二進制文件,下面是代碼片段: 我首先將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
什麼錯嗎?
請後'newZip'並更正intendation'爲'並且請添加'import zipfile' –
對我來說看起來非常合適用Python3 +進行了最小的變化和工作測試 –
也可以在Python 2.7中使用它可能是2.3中的錯誤或者其他錯誤 - 你是否試圖打開它與不同的zip程序? – Tisho