2009-01-28 78 views
1

我正在尝试解压缩发送给我的一些彩信。问题是,有时它有效,而其他的则不行。当它不起作用时,python zipfile模块会抱怨并说这是一个不好的zip文件。但是使用unix unzip命令解压缩zip文件。ZipFile抱怨,有没有办法使用zipfile模块?

这是香港专业教育学院得到了

zippedfile = open('%stemp/tempfile.zip' % settings.MEDIA_ROOT, 'w+') 
zippedfile.write(string) 
z = zipfile.ZipFile(zippedfile) 

我使用“W +”,写一个字符串到它,该字符串包含一个base64解码的zip文件的字符串表示。

然后,我这样做:

filelist = z.infolist() 
images = [] 

for f in filelist: 
    raw_mimetype = mimetypes.guess_type(f.filename)[0] 
    if raw_mimetype: 
     mimetype = raw_mimetype.split('/')[0] 
    else: 
     mimetype = 'unknown' 
    if mimetype == 'image': 
     images.append(f.filename) 

这样,我已经得到了zip文件的所有图像的列表。但这并不总是有效,因为zipfile模块抱怨一些文件。

有没有办法做到这一点,而无需使用压缩文件模块?

我能以某种方式使用UNIX命令解压,而不是压缩文件,然后以同样的事情,以检索所有从存档的图像?

回答

4

你应该写压缩数据到它时,很有可能以二进制方式打开,该文件。也就是说,您应该使用

zippedfile = open('%stemp/tempfile.zip' % settings.MEDIA_ROOT, 'wb+') 
+0

对不起,这没有帮助,它仍然抱怨一个错误的zip文件。不要惊讶,因为代码有时会起作用。 – espenhogbakk 2009-01-28 17:51:28

0

您可能必须关闭并重新打开文件,或者可能在写入文件后寻找文件的开始位置。

filename = '%stemp/tempfile.zip' % settings.MEDIA_ROOT 
zippedfile = open(filename , 'wb+') 
zippedfile.write(string) 
zippedfile.close() 
z = zipfile.ZipFile(filename,"r") 

你说的字符串是base64解码,但你没有显示任何代码解码它 - 你确定它还没有编码?

data = string.decode('base64') 
+0

对不起,这没有帮助,我实际上得到一个错误,我无法执行一个关闭的文件上的I/O操作,当我尝试。 – espenhogbakk 2009-01-28 17:52:07