Compress Directory into Zip File

  • Share this:

Code introduction


This function compresses the specified directory and all its subdirectories and files into a single zip file.


Technology Stack : os, zipfile

Code Type : File compression

Code Difficulty : Intermediate


                
                    
def zip_file(file_path, destination_path):
    import os
    import zipfile

    def zip_directory(directory, zip_path):
        for foldername, subfolders, filenames in os.walk(directory):
            for filename in filenames:
                file_path = os.path.join(foldername, filename)
                arcname = os.path.relpath(file_path, directory)
                zip_path.write(file_path, arcname)

    with zipfile.ZipFile(destination_path, 'w') as zipf:
        zip_directory(file_path, zipf)                
              
Tags: