0
0
PythonHow-ToBeginner · 3 min read

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_dir to 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_name should 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

ParameterDescriptionExample
base_nameOutput archive file name without extension'backup'
formatArchive format: 'zip', 'tar', 'gztar', 'bztar', 'xztar''zip'
root_dirDirectory to archive'my_folder'
base_dirSubdirectory 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.