Last updated: Apr 11, 2024
Reading time·5 min
zipfile
module to zip a directory in PythonUse the shutil.make_archive()
method to create a zip archive of a directory
in Python.
The method creates an archive file (such as zip
or tar
) and returns its
name.
import shutil path_to_dir = './my-directory' output_filename = 'my-zip' shutil.make_archive(output_filename, 'zip', path_to_dir) print('Zip archive of directory created.')
Running the code sample with python main.py
produces a file named my-zip.zip
located in the same directory as your Python script.
The
shutil.make_archive()
method creates an archive file (such as zip
or tar
) and returns its name.
If you print the output of calling the shutil.make_archive()
method, you will
see the path to the newly created zip file.
import shutil path_to_dir = './my-directory' output_filename = 'my-zip' # 👇️ /home/borislav/Desktop/bobbyhadz_python/my-zip.zip print( shutil.make_archive(output_filename, 'zip', path_to_dir) ) print('Zip archive of directory created.')
The shutil.make_archive
method should be your preferred approach when you need
to zip a directory recursively.
The first argument we passed to the method is the base_name
.
The base_name
is the name of the zip
file to be created, including the path,
excluding a format-specific extension.
Notice that we didn't specify the extension in the first argument.
The second argument the method takes is the format
.
The format
argument can be one of:
zip
(if the zlib
module is available)tar
gztar
(if the zlib
module is available)bztar
(if the bz2
module is available)xztar
(if the lzma
module is available)The third argument we passed to the method is the root directory of the archive.
All paths in the archive will be relative to the specified root directory.
zipfile
module to zip a directory in PythonYou can also use the zipfile module to zip a directory in Python.
The module provides classes and methods that enable you to create, read, write, append and list a ZIP file.
import os import zipfile def zip_directory(path, zip_file_handle): for root, _dirs, files in os.walk(path): for file in files: zip_file_handle.write( os.path.join(root, file), os.path.relpath( os.path.join(root, file), os.path.join(path, '..') ) ) print(f'Directory {path} zipped successfully') path_to_dir = './my-directory' output_filename = 'my-zip.zip' with zipfile.ZipFile( output_filename, 'w', zipfile.ZIP_DEFLATED) as zip_file: zip_directory(path_to_dir, zip_file)
We used the
zipfile.ZipFile
class to open a ZIP file in w
(write) mode.
path_to_dir = './my-directory' output_filename = 'my-zip.zip' with zipfile.ZipFile( output_filename, 'w', zipfile.ZIP_DEFLATED) as zip_file: zip_directory(path_to_dir, zip_file)
We passed the following argument to the class:
.zip
file.r
(read), w
(write), a
(append) or x
(exclusive
create).zipfile.ZIP_DEFLATED
compression is a numeric
constant for the usual ZIP compression method. Make sure the
zlib module is
available to be able to use the constant.The zip_directory
function takes the path to the directory and the zip file
handle and creates a zip of the contents of the directory.
The os.walk() method generates the file names in a directory tree by walking the tree top-down.
The tuple contains:
import os import zipfile def zip_directory(path, zip_file_handle): for root, _dirs, files in os.walk(path): for file in files: zip_file_handle.write( os.path.join(root, file), os.path.relpath( os.path.join(root, file), os.path.join(path, '..') ) ) print(f'Directory {path} zipped successfully')
On each iteration, we use the ZipFile.write()
method to write the current file
to the archive.
We passed the following 2 arguments to the ZipFile.write() method:
You can simplify the code sample a bit by using the pathlib.Path
class.
import zipfile from pathlib import Path def zip_directory(directory, filename): directory = Path(directory) with zipfile.ZipFile( filename, "w", zipfile.ZIP_DEFLATED ) as zip_file: for entry in directory.rglob("*"): zip_file.write(entry, entry.relative_to(directory)) print('Zip archive created successfully') path_to_dir = './my-directory' output_filename = 'my-zip.zip' zip_directory(path_to_dir, output_filename)
The pathlib.Path class takes one or more path segments as parameters and creates a PosixPath or a WindowsPath, depending on the operating system.
We no longer have to write code that handles each operating system, so the code sample is a bit more concise.
You can also use the python -m zipfile
command to create a zip archive of a
directory.
python -m zipfile -c my-zip.zip my-directory # or with python3 (macOS and Linux) python3 -m zipfile -c my-zip.zip my-directory # or with py alias (Windows) py -m zipfile -c my-zip.zip my-directory
my-zip.zip
placeholder with the name of your output zip file and the my-directory
placeholder with the path to the directory you want to zip.Depending on your operating system, you might have to use the python3
or py
(Windows) command instead.
The commands from the example should be issued in your terminal (e.g. CMD, bash, zsh).
If you don't want to zip the parent directory, use the /*
suffix.
python -m zipfile -c my-zip.zip "my-directory/*" # or with python3 (macOS and Linux) python3 -m zipfile -c my-zip.zip "my-directory/*" # or with py alias (Windows) py -m zipfile -c my-zip.zip "my-directory/*"
If you need to create a zip archive of a Python application, use the built-in zipapp module.
python -m zipapp my_application python my_application.pyz # or with python3 python3 -m zipapp my_application python3 my_application.pyz # or with py alias (Windows) py -m zipapp my_application py my_application.pyz
The zipapp
module is used for managing executable Python zip archives.
Make sure to replace the my_application
placeholder with the actual name of
your Python application.
You can also specify the function to be invoked when you run the .pyz
file.
python -m zipapp myapp -m "myapp:main" python myapp.pyz
When you run the myapp.pyz
file, the main
function from the archive is
invoked.
I've also written an article on how to unzip a .gz file using Python.
You can learn more about the related topics by checking out the following tutorials: