Compress files in Python

1
189
Compress files in Python

This is a coding tip article. I will show you how to compress files in Python.

We will create Zip archive file through coding.

Article Contents

Compress files in Python

There are two common methods:

  • Using zipfile library.
  • Using shutil library.

Both libraries are equivalent to each other in term of making compressed files.

1. Using zipfile

import zipfile

z = zipfile.ZipFile('final.zip', 'w', zipfile.ZIP_DEFLATED)
z.write('file1.txt')
z.write('file2.txt')
z.close()

The 3rd argument of the ZipFile constructor is for compressing algorithm. Following are the supported methods:

ZIP_STORED = 0
ZIP_DEFLATED = 8
ZIP_BZIP2 = 12
ZIP_LZMA = 14

Keep calling write() to input files to put into the compressed archive.

Call close() when you finish. The final ZIP archive will be generated shortly.

2. Using shutil

To create ZIP archive for a single file.

import shutil

shutil.make_archive('final', 'zip', './', 'file.txt')

To create ZIP archive for a whole directory.

import shutil

shutil.make_archive('final', 'zip', './', 'data')

List of parameters is below:

  • First parameter is the archive filename (without extension).
  • Second one is the archive format.
  • Third one is the path where to save the archive.
  • Last parameter is either a file or a directory to compress.

Conclusion

Picking up the one you feel comfortable with. I myself use ZipFile library to compress files in Python, and don’t use shutil.

In addition, make sure to checkout the official documentation for any update.