10

I've got a folder called: 'files' which contains lots of jpg photographs. I've also got a file called 'temp.kml'. I want to create a KMZ file (basically a zip file) which contains the temp.kml file AND the files directory which has the photographs sitting inside it.

Here is my code:

zfName = 'simonsZip.kmz'
foo = zipfile.ZipFile(zfName, 'w')
foo.write("temp.kml")
foo.close()
os.remove("temp.kml")

This creates the kmz file and puts the temp.kml inside. But I also want to put the folder called 'files' in as well. How do I do this?

I read here on StackOverflow that some people have used shutil to make zip files. Can anyone offer a solution?

Blaszard
  • 30,954
  • 51
  • 153
  • 233
BubbleMonster
  • 1,366
  • 8
  • 32
  • 48
  • 2
    Does this answer your question? [How to create a zip archive of a directory in Python?](https://stackoverflow.com/questions/1855095/how-to-create-a-zip-archive-of-a-directory-in-python) – Marcello Fabrizio Oct 22 '20 at 13:02

2 Answers2

36

You can use shutil

import shutil

shutil.make_archive("simonsZip", "zip", "files")
Drewness
  • 5,004
  • 4
  • 32
  • 50
  • @radtek - based on the OP's question there was not an obvious concern for being on a legacy version of Python, but I see your point. ;) – Drewness Jan 28 '15 at 19:42
  • I'm dealing with python 2.5, hopefully not for long. So zipfile module works for me. zipfile & shutil are available in 3.x – radtek Jan 29 '15 at 16:08
  • This looks a nice solution but in my case I want to zip the directory provided and not the contents of the directory, which results in a zip-bomb. Is there anyway to do this. I am trying to replcate what the 7zip right click on a directory is doing. – thanos.a Oct 25 '17 at 10:07
13

The zipfile module in python has no support for adding a directory with file so you need to add the files one by one.

This is an (untested) example of how that can be achieved by modifying your code example:

import os

zfName = 'simonsZip.kmz'
foo = zipfile.ZipFile(zfName, 'w')
foo.write("temp.kml")
# Adding files from directory 'files'
for root, dirs, files in os.walk('files'):
    for f in files:
        foo.write(os.path.join(root, f))
foo.close()
os.remove("temp.kml")
HAL
  • 2,011
  • 17
  • 10
  • 1
    To get compression not just store -> zipfile.ZipFile('myzip.zip', "w", zipfile.ZIP_DEFLATED) – radtek Jan 27 '15 at 14:58