Zip and Delete Directory into Single Zip File

  • Share this:

Code introduction


This function zips all files in a specified directory into a single zip file and then deletes the original directory.


Technology Stack : os, zipfile, json, shutil

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_file_directory(directory_path, file_name):
    """
    This function zips all the files in a given directory into a single zip file.
    """
    import os
    import zipfile
    import json
    import shutil

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

    # Remove the directory after zipping
    shutil.rmtree(directory_path)

    return zip_path