How do I zip the contents of a folder using python (version 2.5)?
On python 2.7 you might use: shutil.make_archive(base_name, format[, root_dir[, base_dir[, verbose[, dry_run[, owner[, group[, logger]]]]]]]).
base_name archive name minus extension
format format of the archive
root_dir directory to compress.
For example
shutil.make_archive(target_file, format="bztar", root_dir=compress_me)
Adapted version of the script is:
#!/usr/bin/env pythonfrom __future__ import with_statementfrom contextlib import closingfrom zipfile import ZipFile, ZIP_DEFLATEDimport osdef zipdir(basedir, archivename): assert os.path.isdir(basedir) with closing(ZipFile(archivename, "w", ZIP_DEFLATED)) as z: for root, dirs, files in os.walk(basedir): #NOTE: ignore empty directories for fn in files: absfn = os.path.join(root, fn) zfn = absfn[len(basedir)+len(os.sep):] #XXX: relative path z.write(absfn, zfn)if __name__ == '__main__': import sys basedir = sys.argv[1] archivename = sys.argv[2] zipdir(basedir, archivename)
Example:
C:\zipdir> python -mzipdir c:\tmp\test test.zip
It creates 'C:\zipdir\test.zip'
archive with the contents of the 'c:\tmp\test'
directory.
Here is a recursive version
def zipfolder(path, relname, archive): paths = os.listdir(path) for p in paths: p1 = os.path.join(path, p) p2 = os.path.join(relname, p) if os.path.isdir(p1): zipfolder(p1, p2, archive) else: archive.write(p1, p2) def create_zip(path, relname, archname): archive = zipfile.ZipFile(archname, "w", zipfile.ZIP_DEFLATED) if os.path.isdir(path): zipfolder(path, relname, archive) else: archive.write(path, relname) archive.close()