Pair and Compress Files into Zip in Output Folder

  • Share this:

Code introduction


This function pairs files from two lists and compresses the paired files into zip files. It then moves the zip files to the specified output folder.


Technology Stack : os, zipfile, shutil

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zipfiles(file_list1, file_list2, output_folder):
    import os
    import zipfile
    import shutil
    
    if not os.path.exists(output_folder):
        os.makedirs(output_folder)
    
    for file1, file2 in zip(file_list1, file_list2):
        zip_filename = f"{os.path.splitext(file1)[0]}_{os.path.splitext(file2)[0]}.zip"
        zip_path = os.path.join(output_folder, zip_filename)
        with zipfile.ZipFile(zip_path, 'w') as zipf:
            zipf.write(file1, arcname=os.path.basename(file1))
            zipf.write(file2, arcname=os.path.basename(file2))
            
        shutil.move(zip_path, os.path.join(output_folder, zip_filename))                
              
Tags: