Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better way to zip files in Python (zip a whole directory with a single command)? [duplicate]

Tags:

python

zip

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
like image 259
Somebody still uses you MS-DOS Avatar asked Aug 31 '10 18:08

Somebody still uses you MS-DOS


3 Answers

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:])
like image 93
dash-tom-bang Avatar answered Sep 21 '22 15:09

dash-tom-bang


You could try using the distutils package:

distutils.archive_util.make_zipfile(base_name, base_dir[, verbose=0, dry_run=0])
like image 35
bosmacs Avatar answered Sep 23 '22 15:09

bosmacs


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

like image 40
inspectorG4dget Avatar answered Sep 23 '22 15:09

inspectorG4dget