我试图在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. (please check that you have transferred or created the zipfile in the appropriate BINARY mode and that you have compiled UnZip properly)
我使用的是python2.3
这里怎么了?在
嗯不确定是不是Python2.3中的bug。当前的工作环境不允许我升级到更高版本的python:-(:-(:-)
以下解决方法有效:
您可能需要升级,因为python2.3已经过时了。2.7.3是2.x版本中的最新版本,3.2.3是最新的python版本。在
见docs.python.org:
(2.6版新增)
看看Zip a folder and its content。在
您可能还对distutlis.archive_util感兴趣。在
相关问题 更多 >
编程相关推荐