Combining Files into Zip with Two Lists

  • Share this:

Code introduction


This function accepts two lists of files and a path to the output folder, combines the files from both lists into zip files, and saves them in the output folder.


Technology Stack : os, zipfile, glob

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zipfiles(file_list1, file_list2, output_folder):
    import os
    import zipfile
    import glob

    # Create output folder if it does not exist
    if not os.path.exists(output_folder):
        os.makedirs(output_folder)

    # Iterate over both file lists and create zip files
    for files1, files2, output_file in zip(file_list1, file_list2, glob.glob(os.path.join(output_folder, '*.zip'))):
        with zipfile.ZipFile(output_file, 'w') as zipf:
            for file in files1:
                zipf.write(file, os.path.basename(file))
            for file in files2:
                zipf.write(file, os.path.basename(file))

    return glob.glob(os.path.join(output_folder, '*.zip'))                
              
Tags: