How to Use shutil to Create Archive in Python
Use
shutil.make_archive() to create archives in Python by specifying the base name, format (like 'zip' or 'tar'), and the root directory to archive. This function compresses the directory into an archive file quickly with simple parameters.Syntax
The shutil.make_archive() function creates an archive file (like zip or tar) from a directory.
- base_name: The name of the output archive file without extension.
- format: The archive format, e.g., 'zip', 'tar', 'gztar', 'bztar', or 'xztar'.
- root_dir: The directory you want to archive.
- base_dir (optional): The directory inside
root_dirto archive. Defaults to the root directory itself.
python
shutil.make_archive(base_name, format, root_dir=None, base_dir=None)
Example
This example creates a zip archive named 'backup.zip' from the folder 'my_folder'. It shows how easy it is to compress a directory using shutil.make_archive().
python
import shutil # Create a zip archive named 'backup.zip' from 'my_folder' directory archive_name = shutil.make_archive('backup', 'zip', 'my_folder') print(f"Archive created: {archive_name}")
Output
Archive created: backup.zip
Common Pitfalls
Common mistakes when using shutil.make_archive() include:
- Not specifying the correct
root_dir, which leads to empty or wrong archives. - Forgetting that
base_nameshould not include the file extension. - Using unsupported formats or typos in the format string.
- Expecting the function to archive individual files instead of directories.
Always check the archive file is created and contains the expected files.
python
import shutil # Wrong: base_name includes extension (wrong) # shutil.make_archive('backup.zip', 'zip', 'my_folder') # This creates 'backup.zip.zip' # Right: base_name without extension shutil.make_archive('backup', 'zip', 'my_folder')
Quick Reference
| Parameter | Description | Example |
|---|---|---|
| base_name | Output archive file name without extension | 'backup' |
| format | Archive format: 'zip', 'tar', 'gztar', 'bztar', 'xztar' | 'zip' |
| root_dir | Directory to archive | 'my_folder' |
| base_dir | Subdirectory inside root_dir to archive (optional) | 'subfolder' |
Key Takeaways
Use shutil.make_archive(base_name, format, root_dir) to create archives easily.
Do not include file extensions in base_name; shutil adds them automatically.
Supported formats include 'zip', 'tar', 'gztar', 'bztar', and 'xztar'.
Make sure root_dir points to the directory you want to compress.
Check the created archive to confirm it contains the expected files.