Randomly Download S3 Bucket Object

  • Share this:

Code introduction


This function randomly selects an object from a specified S3 bucket and downloads it to the local machine. It first lists all objects in the bucket, then randomly selects an object, and finally downloads it locally using boto3's download_file method.


Technology Stack : boto3, S3

Code Type : The type of code

Code Difficulty : Intermediate


                
                    
import boto3
import random

def random_s3_object_download(bucket_name, object_key):
    """
    This function randomly selects an object from a specified S3 bucket and downloads it.
    """
    s3 = boto3.client('s3')
    response = s3.list_objects_v2(Bucket=bucket_name)
    if 'Contents' not in response:
        print("Bucket is empty or does not exist.")
        return

    objects = response['Contents']
    if not objects:
        print("No objects found in the bucket.")
        return

    # Select a random object
    random_object = random.choice(objects)
    random_key = random_object['Key']

    # Download the object
    s3.download_file(bucket_name, random_key, f"{random_key}.downloaded")

    print(f"Object {random_key} has been downloaded.")                
              
Tags: