Compress and Archive Files with ZIP, TAR, GZIP, and BZ2

  • Share this:

Code introduction


This function compresses two files into different formats: ZIP, TAR, GZIP, and BZ2. It also integrates geographic spatial data into Python using the ArcGIS library.


Technology Stack : os, zipfile, shutil, tarfile, gzip, bz2, arcgis

Code Type : File compression and decompression

Code Difficulty : Intermediate


                
                    
def zip_file(file1, file2):
    import os
    import zipfile
    import shutil
    import tarfile
    import gzip
    import bz2
    import arcgis

    base_name = os.path.splitext(os.path.basename(file1))[0]
    zip_path = f"{base_name}.zip"
    tar_path = f"{base_name}.tar"
    gzip_path = f"{base_name}.gz"
    bz2_path = f"{base_name}.bz2"

    # Create a zip file
    with zipfile.ZipFile(zip_path, 'w') as zipf:
        zipf.write(file1)
        zipf.write(file2)

    # Create a tar file
    with tarfile.open(tar_path, 'w') as tar:
        tar.add(file1)
        tar.add(file2)

    # Compress using gzip
    with gzip.open(gzip_path, 'wb') as gz:
        with open(file1, 'rb') as f:
            gz.writelines(f)

    # Compress using bz2
    with bz2.open(bz2_path, 'wb') as bz:
        with open(file1, 'rb') as f:
            bz.writelines(f)

    # Cleanup temporary files
    for f in [zip_path, tar_path, gzip_path, bz2_path]:
        os.remove(f)

    return f"Files {file1} and {file2} have been compressed into {zip_path}, {tar_path}, {gzip_path}, and {bz2_path}"