[Python] boto3: How to Find Prefix of S3 Object and Update Object Given the Filename?

Discussão em 'Python' iniciado por Stack, Março 24, 2025.

  1. Stack

    Stack Membro Participativo

    I have a populated S3 bucket and a filename I want to search for and update. The bucket has an existing list of objects (with prefixes). I am trying to make an API call to the bucket to update a given object. However, I need to search through all the objects in the bucket (including all prefixes), and then update it (via an s3 file upload) if it matches the current filename.

    For example, my bucket has the following in root:

    cat2.jpg
    cat3.jpg
    PRE CAT_PICS/cat.jpg
    PRE CAT_PICS/cat2.jpg
    PRE CAT_PICS/MORE_CAT_PICS/cat3.jpg


    If I want to "recursively" search through all objects, match, and update cat3.jpg how could I do that? Additionally, is there a way to extract the prefix of the found object? I have some code already but I am not sure if it is correct. It also cannot cover more than 1000 objects since it lacks pagination:

    My Current Code:

    import boto3

    FILE_TO_UPDATE = cat3.jpg

    s3_bucket = "example_bucket2182023"
    s3_client = boto3.client("s3")

    for my_bucket_object in my_bucket.objects.all():
    if my_bucket_object.endswith(FILE_TO_UPDATE):
    try:
    s3_client.put_object(
    Bucket=s3_bucket,
    key=my_bucket_object
    )
    except:
    print(f"Error uploading {my_bucket_object} to {s3_bucket}")

    print(my_bucket_object.key)

    Continue reading...

Compartilhe esta Página