Compress Two Files into a Zip File

  • Share this:

Code introduction


This function compresses two files into a single zip file and returns the path of the generated zip file.


Technology Stack : os, zipfile, shutil

Code Type : File compression

Code Difficulty : Intermediate


                
                    
def zip_file(file1, file2):
    import os
    import zipfile
    import shutil
    
    def create_zip_folder(folder_path):
        if not os.path.exists(folder_path):
            os.makedirs(folder_path)
    
    zip_folder = 'combined_files'
    create_zip_folder(zip_folder)
    zip_path = os.path.join(zip_folder, 'combined.zip')
    
    with zipfile.ZipFile(zip_path, 'w') as zipf:
        zipf.write(file1, os.path.basename(file1))
        zipf.write(file2, os.path.basename(file2))
    
    shutil.rmtree(zip_folder)
    
    return zip_path                
              
Tags: