SoFunction
Updated on 2025-04-15

Python two common ways to decompress files or folders (with code)

Preface

In daily development or data processing, we often need to compress and decompress files or folders. Python provides powerful built-in modules such aszipfileandshutil, can help us complete these tasks efficiently.

This article will introduce how to use Python to compress and decompress folders or files, including two common ways:zipfileandshutil, and provide complete code examples.

Compress files or folders

1. Use the zipfile module to compress the folder

zipfileModules are part of the Python standard library for creating and reading.zipdocument. It supports fine control of the content and path of file compression.

The following is a compressed folder into.zipFile code example:

import os
import zipfile

def compress_folder_to_zip(folder_path, zip_path):
    with (zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
        for root, dirs, files in (folder_path):
            for file in files:
                file_path = (root, file)
                # When adding to a ZIP file, retain the relative path                arcname = (file_path, folder_path)
                (file_path, arcname)
    print(f"Compression is complete:{zip_path}")

# Example usagecompress_folder_to_zip('path/to/folder', '')

Code description:

  • Transfer all files in the folder and its subfolders.
  • Make sure that the compressed file path is relative to the original folder path.
  • zipfile.ZIP_DEFLATEDSpecify the compression algorithm.

2. Use the shutil module to compress folders

If you just need to compress the folder into.zipor.tarFiles can be usedshutilModule. It supports a variety of compression formats, includingziptargztarwait.

The code example is as follows:

import shutil

def compress_with_shutil(folder_path, output_path, format='zip'):
    # format supports "zip", "tar", "gztar", "bztar", "xztar"    shutil.make_archive(output_path, format, folder_path)
    print(f"Compression is complete:{output_path}.{format}")

# Example usagecompress_with_shutil('path/to/folder', 'output', 'zip')

Code description:

  • shutil.make_archiveThe method automatically completes the compression process.output_pathNo extension is required.
  • formatThe parameters support multiple formats, just select the appropriate compression format.

Unzip the file

1. Use zipfile to decompress the .zip file

usezipfileModule, we can unzip.zipFile to the specified directory:

import zipfile

def extract_zip(zip_path, extract_to):
    with (zip_path, 'r') as zipf:
        (extract_to)
    print(f"Decompression is complete:{extract_to}")

# Example usageextract_zip('', 'path/to/extract')

Code description:

  • ()It will decompress everything in the ZIP file to the specified path.
  • Suitable for scenarios where custom decompression logic is required.

2. Use shutil to unzip the file

If the file is.zipFormat, and no complex operations are required, you can useshutilQuickly decompress:

import shutil

def extract_with_shutil(zip_path, extract_to):
    shutil.unpack_archive(zip_path, extract_to)
    print(f"Decompression is complete:{extract_to}")

# Example usageextract_with_shutil('', 'path/to/extract')

Code description:

  • shutil.unpack_archiveSupports decompression of multiple format files, such as.zipand.tar
  • Suitable for quick decompression tasks.

Complete example: Combination of compression and decompression

Here is a complete Python script that includes compression and decompression capabilities:

import os
import zipfile
import shutil

def compress_folder(folder_path, zip_path):
    with (zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
        for root, dirs, files in (folder_path):
            for file in files:
                file_path = (root, file)
                arcname = (file_path, folder_path)
                (file_path, arcname)
    print(f"Compression is complete:{zip_path}")

def decompress_folder(zip_path, extract_to):
    with (zip_path, 'r') as zipf:
        (extract_to)
    print(f"Decompression is complete:{extract_to}")

# Example usageif __name__ == "__main__":
    # Compress folders    compress_folder('path/to/folder', '')
    # Unzip the ZIP file    decompress_folder('', 'path/to/extract')

Summarize

In this article, we learned how to use PythonzipfileandshutilThe module performs compression and decompression of folders and files:

  • zipfile module: Suitable for scenarios that require fine control, such as custom compression paths.
  • shutil module: Quickly complete compression and decompression, suitable for simple tasks.

Whether you need to compress multiple files or want to quickly decompress a folder, both methods can meet your needs.

This is the end of this article about two common ways to decompress files or folders in Python. For more related contents of python decompress files or folders, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!