3

So I'm having an issue with using the zipfile module in Python. Currently when I try to compress a KML file to create a new KMZ file I'm missing the last few lines. It doesn't seem to matter how long the KML is. I assume this is because zipfile isn't writing the last zipped block.

kmz = zipfile.ZipFile(kmzPath , 'w')
kmz.write(kmlPath, 'CORS.kml', zipfile.ZIP_DEFLATED)

And yes before you ask I have imported zlib to do the compression. I've tried to use zlib at the lower level too but have the same issue. I'm stuck.

Any ideas?

Dharman
  • 30,962
  • 25
  • 85
  • 135
koax26
  • 163
  • 1
  • 6

2 Answers2

3

Make sure that you called

kmz.close()

after the .write(...) command, otherwise the full contents of the file won't be flushed to disk. To make sure this happens automatically, always use the with context manager, as the file will be closed when the loop is exited:

with zipfile.ZipFile(kmzPath, 'w') as kmz:
    kmz.write(kmlPath, 'CORS.kml', zipfile.ZIP_DEFLATED)
MattDMo
  • 100,794
  • 21
  • 241
  • 231
  • Hey yeah alright. Thats worked. I usually use **with** as well but got an _AttributeError: ZipFile instance has no attribute '__exit__'_ so thats why it was left out. Since I almost never use *.close() I forgot. Bugger. Thanks! – koax26 Sep 12 '14 at 04:30
0

This is just a guess, but according to the zipfile documentation:

You must call close() before exiting your program or essential records will not be written.

You don't indicate that you are in fact calling kmz.close() - could that be the problem?

Zero Piraeus
  • 56,143
  • 27
  • 150
  • 160