Decompressing ZIP, TAR, GZIP, and BZ2 Files

  • Share this:

Code introduction


This function is designed to decompress different compressed files (ZIP, TAR, GZIP, BZ2) into a specified directory.


Technology Stack : os, zipfile, shutil, tarfile, gzip, bz2, tar, io

Code Type : File processing

Code Difficulty : Intermediate


                
                    
def zipfiles(file1, file2):
    import os
    import zipfile
    import shutil
    import tarfile
    import gzip
    import bz2
    import tar
    import io

    def zip_to_zip(file_path, output_path):
        with zipfile.ZipFile(file_path, 'r') as zip_ref:
            zip_ref.extractall(output_path)

    def tar_to_zip(file_path, output_path):
        with tarfile.open(file_path, 'r') as tar_ref:
            tar_ref.extractall(output_path)

    def gzip_to_zip(file_path, output_path):
        with gzip.open(file_path, 'rb') as gzip_ref:
            with zipfile.ZipFile(output_path, 'w', zipfile.ZIP_DEFLATED) as zip_ref:
                zip_ref.writestr(os.path.basename(file_path), gzip_ref.read())

    def bz2_to_zip(file_path, output_path):
        with bz2.open(file_path, 'rb') as bz2_ref:
            with zipfile.ZipFile(output_path, 'w', zipfile.ZIP_DEFLATED) as zip_ref:
                zip_ref.writestr(os.path.basename(file_path), bz2_ref.read())

    if file1.endswith('.zip'):
        zip_to_zip(file1, 'output')
    elif file1.endswith('.tar'):
        tar_to_zip(file1, 'output')
    elif file1.endswith('.gz'):
        gzip_to_zip(file1, 'output')
    elif file1.endswith('.bz2'):
        bz2_to_zip(file1, 'output')
    else:
        raise ValueError("Unsupported file type")

    return 'output'