views:

232

answers:

2

Hi,

I am trying to decompress some MMS messages sent to me zipped. The problem is that sometimes it works, and others not. And when it doesnt work, the python zipfile module complains and says that it is a bad zip file. But the zipfile decompresses fine using the unix unzip command.

This is what ive got

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

I am using 'w+' and writing a string to it, the string contains a base64 decoded string representation of a zip file.

Then I do like this:

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)

This way I've got a list of all the images in the zip file. But this doesnt always work, since the zipfile module complains about some of the files.

Is there a way to do this, without using the zipfile module?

Could I somehow use the unix command unzip instead of zipfile and then to the same thing to retrive all the images from the archive?

+2  A: 

You should very probably open the file in binary mode, when writing zipped data into it. That is, you should use

zippedfile = open('%stemp/tempfile.zip' % settings.MEDIA_ROOT, 'wb+')
unwind
Sorry, this doesnt help, it still complains about a bad zipfile. Not suprising since the code does work sometimes.
Espen Christensen
A: 

You might have to close and reopen the file, or maybe seek to the start of the file after writing it.

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

You say the string is base64 decoded, but you haven't shown any code that decodes it - are you sure it's not still encoded?

data = string.decode('base64')
Douglas Leeder
Sorry, this doesnt help, i actally get an error that i cant perform an I/O operation on a closed file when i try that.
Espen Christensen