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
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:])
You could try using the distutils package:
distutils.archive_util.make_zipfile(base_name, base_dir[, verbose=0, dry_run=0])
You might also be able to get away with using the zip
command available in the Unix shell with a call to os.system
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With