tags:

views:

93

answers:

1

I am trying to use the zipfile module in Python to create simple zip files:

import zipfile

files = ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h')
zip_file_name = 'zipfile_test.zip'

zfh = zipfile.ZipFile(zip_file_name, 'w')
for file in files:
  print 'Archiving file %s' % file
  zfh.write(zip_file_name)
zfh.close()

The files a-h are in my working directory and are empty, use touch a b c d e f g h to test.

After adding the first 7 items to the zip file, it hangs on the last one but keeps writing to the zip file until space is exhausted. This happens on the two systems I have tested it on, one with Python 2.4.3, the other with Python 2.6.2. If the number of files is less than 6 or 7, the zip file is created without any problems. Otherwise it fails after between 7-15 files and start writing junk to the end of the file. I have tried changing:

  zfh.write(zip_file_name)

to:

  zfh.write(zip_file_name, zip_file_name, zipfile.ZIP_DEFLATED)

which sometimes allows me to write a couple more files but inevitably fails as well.

What am I doing wrong?

+5  A: 

You're putting the zip file into the zip file:

zfh.write(zip_file_name)

Should be:

zfh.write(file)
Jon-Eric
Wow, I can't believe I didn't see that, thanks!
Robert Gamble
Thats the kind of mistake thats difficult to spot without a fresh pair of eyes.
Tom