Compress Directory into Zip and Generate Metadata JSON

  • Share this:

Code introduction


This function compresses all files in the specified directory into a zip file and generates a JSON file containing metadata.


Technology Stack : os, zipfile, json, datetime

Code Type : File compression

Code Difficulty : Intermediate


                
                    
def zip_file(file_path, destination):
    import os
    import zipfile
    import json
    import datetime

    # Create a zip file
    with zipfile.ZipFile(destination, 'w') as zipf:
        # Walk through the directory
        for root, dirs, files in os.walk(file_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, file_path))

    # Create a JSON file with metadata
    metadata = {
        "created_at": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
        "files_count": len(os.listdir(file_path)),
        "file_path": file_path,
        "destination": destination
    }
    with open(os.path.join(os.path.dirname(destination), 'metadata.json'), 'w') as json_file:
        json.dump(metadata, json_file)

    return destination