Compress Files into Zip Archive

  • Share this:

Code introduction


This function takes a list of files and compresses them into a single zip file, which is then saved in the specified output folder.


Technology Stack : os, zipfile, pathlib

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zipfiles(file_list, output_folder):
    import os
    import zipfile
    from pathlib import Path

    # Ensure output folder exists
    Path(output_folder).mkdir(parents=True, exist_ok=True)

    # Create a zip file in the output folder
    zip_filename = f"{output_folder}/files.zip"
    with zipfile.ZipFile(zip_filename, 'w') as zipf:
        for file in file_list:
            # Add each file to the zip file
            zipf.write(file, arcname=file)

    return zip_filename