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
  • 29,431
  • 45
  • 147
  • 228
BubbleMonster
  • 1,326
  • 7
  • 31
  • 47
  • 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

3 Answers3

34

You can use shutil

import shutil

shutil.make_archive("simonsZip", "zip", "files")
Drewness
  • 4,879
  • 4
  • 31
  • 49
  • @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
12

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
  • 1,891
  • 16
  • 10
  • 1
    To get compression not just store -> zipfile.ZipFile('myzip.zip', "w", zipfile.ZIP_DEFLATED) – radtek Jan 27 '15 at 14:58
0

Actually, I think this is the best answer so far here You don't have to loop through anything. You will use shutil and it is a python in-built library.

Cyborg_Trick
  • 155
  • 2
  • 12