Compress Directory into Zip File

  • Share this:

Code introduction


This function compresses all files in the specified directory into a zip file.


Technology Stack : os, zipfile, shutil

Code Type : File processing

Code Difficulty : Intermediate


                
                    
def zip_file(directory, filename):
    import os
    import zipfile
    import shutil

    # Create a zip file at the specified directory with the given filename
    zip_path = os.path.join(directory, filename + '.zip')
    with zipfile.ZipFile(zip_path, 'w') as zipf:
        for foldername, subfolders, filenames in os.walk(directory):
            for filename in filenames:
                file_path = os.path.join(foldername, filename)
                zipf.write(file_path, os.path.relpath(file_path, directory))

    return zip_path                
              
Tags: