pythonkmlpython-2.6kmzpython-zipfile

zipfile is leaving the last few lines off my file - why?


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?


Solution

  • 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)