This is a coding tip article. I will show you how to compress files in Python.
We will create Zip archive file through coding.
Compress files in Python
There are two common methods:
Both libraries are equivalent to each other in term of making compressed files.
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
write() to input files to put into the compressed archive.
close() when you finish. The final ZIP archive will be generated shortly.
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.
Picking up the one you feel comfortable with. I myself use
ZipFile library to compress files in Python, and don’t use
In addition, make sure to checkout the official documentation for any update.