Compress and Convert File Formats

  • Share this:

Code introduction


This function can compress files in different formats (zip, tar, gz, bz2) into another file. If the input file is in zip or tar format, it will move the file directly; if it is in gz or bz2 format, it will be compressed using gzip or bz2 respectively.


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

Code Type : Function

Code Difficulty : Intermediate


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

    def zip_dir(source_dir, zip_name):
        with zipfile.ZipFile(zip_name, 'w') as zipf:
            for root, dirs, files in os.walk(source_dir):
                for file in files:
                    file_path = os.path.join(root, file)
                    zipf.write(file_path, os.path.relpath(file_path, source_dir))

    def tar_dir(source_dir, tar_name):
        with tarfile.open(tar_name, "w") as tar:
            for root, dirs, files in os.walk(source_dir):
                for file in files:
                    file_path = os.path.join(root, file)
                    tar.add(file_path, arcname=os.path.relpath(file_path, source_dir))

    def gzip_file(file_path, gzip_name):
        with open(file_path, 'rb') as f_in:
            with gzip.open(gzip_name, 'wb') as f_out:
                shutil.copyfileobj(f_in, f_out)

    def bz2_file(file_path, bz2_name):
        with open(file_path, 'rb') as f_in:
            with bz2.open(bz2_name, 'wb') as f_out:
                shutil.copyfileobj(f_in, f_out)

    if zipfile.is_zipfile(file1):
        shutil.move(file1, file2)
    elif tarfile.is_tarfile(file1):
        tar_dir(file1, file2)
    elif file1.endswith('.gz'):
        gzip_file(file1, file2)
    elif file1.endswith('.bz2'):
        bz2_file(file1, file2)
    else:
        zip_dir(file1, file2)