Compressing Files with Multiple Formats in Python

  • Share this:

Code introduction


The function, based on the file type, uses different built-in libraries to package two files into different formats: ZIP, TAR, GZIP, BZ2. If a suitable library is not found, an exception is thrown.


Technology Stack : The function, based on the file type, uses different built-in libraries to package two files into different formats: ZIP, TAR, GZIP, BZ2. If a suitable library is not found, an exception is thrown.

Code Type : Function

Code Difficulty :


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

    def create_zip(file1, file2):
        with zipfile.ZipFile('output.zip', 'w') as zipf:
            zipf.write(file1, os.path.basename(file1))
            zipf.write(file2, os.path.basename(file2))

    def create_tar(file1, file2):
        with tarfile.open('output.tar', 'w') as tarf:
            tarf.add(file1, arcname=os.path.basename(file1))
            tarf.add(file2, arcname=os.path.basename(file2))

    def create_gzip(file1, file2):
        with gzip.open('output.gz', 'wb') as gzf:
            with open(file1, 'rb') as f1, open(file2, 'rb') as f2:
                gzf.writelines(f1)
                gzf.writelines(f2)

    def create_bz2(file1, file2):
        with bz2.open('output.bz2', 'wb') as bzf:
            with open(file1, 'rb') as f1, open(file2, 'rb') as f2:
                bzf.writelines(f1)
                bzf.writelines(f2)

    if zipfile.__name__ in globals():
        create_zip(file1, file2)
    elif tarfile.__name__ in globals():
        create_tar(file1, file2)
    elif gzip.__name__ in globals():
        create_gzip(file1, file2)
    elif bz2.__name__ in globals():
        create_bz2(file1, file2)
    else:
        raise RuntimeError("No suitable compression library found.")