8

Possible Duplicate:
How do I zip the contents of a folder using python (version 2.5)?

Suppose I have a directory: /home/user/files/. This dir has a bunch of files:

/home/user/files/
  -- test.py
  -- config.py

I want to zip this directory using ZipFile in python. Do I need to loop through the directory and add these files recursively, or is it possible do pass the directory name and the ZipFile class automatically adds everything beneath it?

In the end, I would like to have:

/home/user/files.zip (and inside my zip, I dont need to have a /files folder inside the zip:)
  -- test.py
  -- config.py
Community
  • 1
  • 1
  • 2
    Since os.walk yields the entire content of the directory -- doing the recursion for you -- it seems like a trivial loop. What are you trying to optimize? Lines of code? I don't see how. Time? Not possible -- Zip takes the time it takes. What problem are you having? – S.Lott Aug 31 '10 at 18:56
  • I just want to zip a folder that may have empty folders, without coding a bunch of lines for something that my Linux machine can do with a single command using the zip utility and the subprocess module. – Somebody still uses you MS-DOS Sep 01 '10 at 17:39

4 Answers4

24

Note that this doesn't include empty directories. If those are required there are workarounds available on the web; probably best to get the ZipInfo record for empty directories in our favorite archiving programs to see what's in them.

Hardcoding file/path to get rid of specifics of my code...

target_dir = '/tmp/zip_me_up'
zip = zipfile.ZipFile('/tmp/example.zip', 'w', zipfile.ZIP_DEFLATED)
rootlen = len(target_dir) + 1
for base, dirs, files in os.walk(target_dir):
   for file in files:
      fn = os.path.join(base, file)
      zip.write(fn, fn[rootlen:])
dash-tom-bang
  • 17,383
  • 5
  • 46
  • 62
  • 1
    In python 3 the `pathlib` module makes this much easier, Use `Path().rglob('*')` like this to add all your files to a ZipFile object: `for _file in Path(path).rglob('*'): zip.write(str(_file))` – Marc Maxmeister Aug 18 '20 at 03:29
7

You could try using the distutils package:

distutils.archive_util.make_zipfile(base_name, base_dir[, verbose=0, dry_run=0])
bosmacs
  • 7,341
  • 4
  • 31
  • 31
2

You might also be able to get away with using the zip command available in the Unix shell with a call to os.system

inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241
1

You could use subprocess module:

import subprocess

PIPE = subprocess.PIPE
pd = subprocess.Popen(['/usr/bin/zip', '-r', 'files', 'files'],
                      stdout=PIPE, stderr=PIPE)
stdout, stderr = pd.communicate()

The code is not tested and pretends to works just on unix machines, i don't know if windows has similar command line utilities.

mg.
  • 7,822
  • 1
  • 26
  • 30