Zipping a directory
Archive files are a good way to distribute whole directories as if they were a single file and to reduce the size of the distributed files.
Python has built-in support for creating ZIP archive files, which can be leveraged to compress a whole directory.
How to do it...
The steps for this recipes are as follows:
- The
zipfile
module allows us to create compressed ZIP archives made up of multiple files:
import zipfile import os def zipdir(archive_name, directory): with zipfile.ZipFile( archive_name, 'w', compression=zipfile.ZIP_DEFLATED ) as archive: for root, dirs, files in os.walk(directory): for filename in files: abspath = os.path.join(root, filename) relpath = os.path.relpath(abspath, directory) archive.write(abspath, relpath)
- Using
zipdir
is as simple as providing a name for the.zip
file that should be created and a path for the directory that should be archived:
zipdir('/tmp/test...