Compress Files into Zip in Output Folder

  • Share this:

Code introduction


This function takes a list of files and a path to an output folder as arguments, compresses all files in the list into a zip file, and stores it in the output folder.


Technology Stack : os, zipfile

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zipfiles(file_list, output_folder):
    import os
    import zipfile

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

    # Create a zip file in the output folder
    zip_filename = os.path.join(output_folder, 'archive.zip')
    with zipfile.ZipFile(zip_filename, 'w') as zipf:
        for file in file_list:
            zipf.write(file, os.path.basename(file))

    return zip_filename                
              
Tags: