Working with zip files in Python

Since I started working with computers, my favorite file format was ‘zip’, popularized by the Windows PKZIP program. The idea of compressing data into shorter versions of themselves was a fascinating idea.

Then, I was ignorant of the mathematical foundations of information theory, so it seemed like magic. I spent umpteen hours playing with file compression – exploring the various options available and seeing how much further I could compress a file. Now compression is a normal part of any computer language library. So when learning Python I first started exploring the compression library.

The Python ‘zipfile’ module can be used to read and write zip files. A simple exampe to view the contents of a zip file is given below.

We can test if file is a zip file regardless the extension.

Also we can test for multiple files.

Which will return.

To extract all the files from the zip archive do the following. This will extract all the file to the current directory.

You can also specify the path.

We can also extract a single file from the zip archive by specifying the file name.

This is just a short overview of the zipfile module. In future posts we will go into other details.

You can test your Python code using the online code editor.

Leave a Reply

Your email address will not be published. Required fields are marked *