Compress Directory to Zip File

  • Share this:

Code introduction


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


Technology Stack : os, zipfile

Code Type : File compression

Code Difficulty : Intermediate


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

    # Create a zip file with the specified filename
    with zipfile.ZipFile(filename, 'w') as zipf:
        # Walk through the directory
        for root, dirs, files in os.walk(directory):
            # Add each file to the zip file
            for file in files:
                file_path = os.path.join(root, file)
                zipf.write(file_path, os.path.relpath(file_path, directory))

    return filename                
              
Tags: