Python Script for Zipping and Extracting File Formats

  • Share this:

Code introduction


gzip, zipfile, tarfile, os


Technology Stack : The packages and technologies used in the code[English]

Code Type : Function

Code Difficulty : Advanced


                
                    
def zip_file(file1, file2, output):
    import os
    import zipfile
    import tarfile
    import gzip

    if os.path.splitext(file1)[1].lower() == '.gz':
        with gzip.open(file1, 'rb') as f1, gzip.open(file2, 'rb') as f2:
            with open(output, 'wb') as f_out:
                f_out.writelines([f1.read(), f2.read()])
    elif os.path.splitext(file1)[1].lower() in ['.zip', '.tar']:
        if os.path.splitext(file1)[1].lower() == '.zip':
            with zipfile.ZipFile(file1, 'r') as z1:
                z1.extractall(output)
            with zipfile.ZipFile(file2, 'r') as z2:
                z2.extractall(output)
        else:
            with tarfile.open(file1, 'r') as t1:
                t1.extractall(output)
            with tarfile.open(file2, 'r') as t2:
                t2.extractall(output)
    else:
        raise ValueError("Unsupported file format")