reading zipfile; problem using raw buffer

Billy Mays 81282ed9a88799d21e77957df2d84bd6514d9af6 at myhashismyemail.com
Tue Jul 26 08:49:44 EDT 2011


On 07/26/2011 08:42 AM, Sells, Fred wrote:
> I'm tring to unzip a buffer that is uploaded to django/python.  I can
> unzip the file in batch mode just fine, but when I get the buffer I get
> a "BadZipfile exception.  I wrote this snippet to try to isolate the
> issue but I don't understand what's going on.  I'm guessing that I'm
> losing some header/trailer somewhere?
>
> def unittestZipfile(filename):
>      buffer = ''
>      f = open(filename)
>      for i in range(22):
>          block = f.read()
>          if len(block) == 0:
>              break
>          else:
>              buffer += block
>
>      print len(buffer)
>      tmp = open('tmp.zip', 'w')
>      tmp.write(buffer)
>      tmp.close()
>      zf = zipfile.ZipFile('tmp.zip')
>      print dir(zf)
>      for name in zf.namelist():
>          print name
>          print zf.read(name)
> ____________________________________________________________
> 2.6.6 (r266:84297, Aug 24 2010, 18:46:32) [MSC v.1500 32 bit (Intel)]
> Traceback (most recent call last):
>    File
> "C:\all\projects\AccMDS30Server\mds30\app\uploaders\xmitzipfile.py",
> line 162, in<module>
>      unittestZipfile('wk1live7.8to7.11.zip')
>    File
> "C:\all\projects\AccMDS30Server\mds30\app\uploaders\xmitzipfile.py",
> line 146, in unittestZipfile
>      print zf.read(name)
>    File "C:\alltools\python26\lib\zipfile.py", line 837, in read
>      return self.open(name, "r", pwd).read()
>    File "C:\alltools\python26\lib\zipfile.py", line 867, in open
>      raise BadZipfile, "Bad magic number for file header"
> zipfile.BadZipfile: Bad magic number for file header
>

You need to specify the file mode since I'm guessing you use Windows 
from the traceback:

f = open(filename, 'rb')

and later:

tmp = open('tmp.zip', 'wb')

--
Bill



More information about the Python-list mailing list