In this article we will discuss how to create a zip archive from selected files or files from a directory based on filters.

Python’s zipfile module provides a ZipFile class for zip file related stuff. Let’s use this to create a zip archive file.

First import the class from module i.e.

Create a zip archive from multiple files in Python

Steps  are,

  • Create 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.

It will create a zip file ‘sample.zip’  with given files inside it.
We can do the same thing with “with open” . It will automatically close the zip file when ZipFile object goes out of scope i.e.

Create a zip archive of a directory

To zip all the contents of a directory in a zip archive, we need to iterate over all the files in directory and it’s sub directories, then add each entry to the zip file using ZipFile.write()

It will zip all the contents of a directory in to a single zip file i..e ‘sampleDir.zip’. It’s contents will be,

Zip selected files from a directory based on filter or wildcards

To zip selected files from a directory we need to check the condition on each file path while iteration before adding it to zip file.

Let’s create function that Iterates over a directory and filter the contents with given callback. Files which pass the filter will only be added in zip i.e.

Let’s zip only csv files from a directory i.e. pass a lambda function as argument in it.

It will create a zip archive ‘sampleDir2.zip’ with all csv files from given directory.

Complete example is as follows:

 

 

Join LinkedIn Group of Python Professional Developers who wish to expand their network and share ideas.

You can also follow us On Twitter :

Click Here to Subscribe for more Articles / Tutorials like this.