Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Once I have all the files I require in a particular folder, I would like my python script to zip the folder contents.

Is this possible?

And how could I go about doing it?

like image 352
Amara Avatar asked Nov 17 '08 19:11

Amara


People also ask

How do you zip contents of a folder?

Press and hold (or right-click) the file or folder, select (or point to) Send to, and then select Compressed (zipped) folder. A new zipped folder with the same name is created in the same location.

How do I zip all files in Python?

Create a zip archive from multiple files in PythonCreate a ZipFile object by passing the new file name and mode as 'w' (write mode). It will create a new zip file and open it within ZipFile object. Call write() function on ZipFile object to add the files in it. call close() on ZipFile object to Close the zip file.

How do I unzip all files in a directory in Python?

To unzip a file in Python, use the ZipFile. extractall() method. The extractall() method takes a path, members, pwd as an argument and extracts all the contents. To work on zip files using Python, we will use an inbuilt python module called zipfile.


2 Answers

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)     
like image 72
jb. Avatar answered Oct 06 '22 00:10

jb.


Adapted version of the script is:

#!/usr/bin/env python from __future__ import with_statement from contextlib import closing from zipfile import ZipFile, ZIP_DEFLATED import os  def 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.

like image 29
jfs Avatar answered Oct 06 '22 00:10

jfs