tags:

views:

141

answers:

6

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
A: 

You could try using the distutils package:

distutils.archive_util.make_zipfile(base_name, base_dir[, verbose=0, dry_run=0])
bosmacs
+1  A: 

I don't know about any shortcuts in the zip module, but there are some snippets out there:

The MYYN
+1  A: 

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
I'm already using subprocess in another section of my script, this is what I was looking for! I didn't think about using zip from *nixes machines, thanks!
Somebody still uses you MS-DOS
A: 

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
A: 

if you are just wanting to zip up python files there is this: http://docs.python.org/library/zipfile.html#pyzipfile-objects

fridder
+2  A: 

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