【发布时间】:2012-07-05 06:20:13
【问题描述】:
我试图在一个 zip 文件中包含一个二进制文件,下面是代码 sn-p: 我首先将 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 模块解压缩它时,我收到以下错误:
压缩文件损坏。 (请检查您是否已转移或 以适当的 BINARY 模式创建了 zipfile,并且您拥有 正确编译解压缩)
我正在使用 python 2.3
这里出了什么问题?
【问题讨论】:
-
请在
newZip和for之后更正您的意图并请添加import zipfile -
对我来说非常合适。使用 Python3 测试 + 最少的更改和工作。
-
也适用于 Python 2.7。要么是 2.3 中的错误,要么是其他错误 - 您是否尝试使用不同的 zip 程序打开它?