Press ESC to close

Write a Program to Compress and Decompress Files using the Zipfile Module in python

Photo by alexdndz

Python is a versatile and most popular programming language. It is easy to learn and always known for its simplicity and readability. Here’s a simple Python program that uses the zipfile module to compress and decompress files. Python programming language is mostly used for machine learning and automation. It’s widely used in various fields such as web development, data analysis, artificial intelligence, scientific computing, and automation, making it one of the most popular languages in the world today.

Compress Files Using zipfile

import zipfile
import os

def compress_files(file_paths, output_zip):
    # Create a ZipFile object in write mode
    with zipfile.ZipFile(output_zip, 'w') as zipf:
        for file in file_paths:
            if os.path.isfile(file):
                zipf.write(file, os.path.basename(file))
                print(f"Compressed: {file}")
            else:
                print(f"File not found: {file}")

# List of files to compress
files_to_compress = ['file1.txt', 'file2.txt', 'file3.txt']
output_zip_file = 'compressed_files.zip'

compress_files(files_to_compress, output_zip_file)
Decompress Files Using zipfile
def decompress_file(zip_file, extract_to):
    # Open the zip file in read mode
    with zipfile.ZipFile(zip_file, 'r') as zipf:
        zipf.extractall(extract_to)
        print(f"Extracted files to: {extract_to}")

# Path to the zip file
zip_file_path = 'compressed_files.zip'
output_folder = './extracted_files'

decompress_file(zip_file_path, output_folder)

Explanation:

  1. Compressing Files:
    • The compress_files function takes a list of file paths and compresses them into a single zip file.
    • zipfile.ZipFile is used to create a zip file in write (‘w’) mode, and zipf.write() adds each file to the archive.
  2. Decompressing Files:
    • The decompress_file function extracts all files from a given zip file to the specified directory.
    • zipfile.ZipFile is used in read (‘r’) mode, and zipf.extractall() extracts all files.

This program handles multiple files for compression and extracts everything from a zip archive when decompressing.

Leave a Reply

Your email address will not be published. Required fields are marked *