Archiving Files Using zipfile & tarfile Modules

zipfile & tarfile in Python

The standard libraries zipfile & tarfile facilitate creating and manipulating zip & Unix tar archive files. The tarfile is not limited to Unix, it can be used in Windows also, and is capable of working with bzip2 & gzip files as well. In this article, we will see how to create archives, append to them, extract them with primitive examples. The idea is to get you started, and then you can search further on how to satisfy your requirements.

zipfile & tarfile

The ZipFile class of zipfile module creates a ZipFile object, which provides us with write() method to create new archive files. The open() function of the tarfile module returns a TarFile object, which provides us with add() method to create archive files.

The ZipFile & TarFile objects provide two methods extract() and extractall() to extract contents from archive files. The extract() extracts the mentioned file from the archive whereas extractall() extracts all contents of the archive.

This article is hardly the complete guide to using zipfile & tarfile standard libraries. It is supposed to give you working snippets to manipulate archive files. For comprehensive examples, follow the links below.