I have been using AWS services for the past 2 years. And if you are wondering why to reupload the same file to the same location. I personally had a case where an AWS lambda function will be triggered whenever a “.json” file is uploaded to the S3 bucket. Also, I did not have console access. So If I need to test a specific file I will have to reupload the same file programmatically. In the article, I have given a simple solution to it.
If you are someone entirely new to AWS click to know what it is and what problem they solve.
You can scroll down to the bottom to view the full code. You want to walk through each step then follow along.
Instantiate the s3 client object using the boto3 library
import boto3
s3_client = boto3.client(‘s3’)
Declare the bucket and prefix in a variable.
BUCKET = ‘ENTER_YOUR_BUCKET_NAME’
PREFIX = ‘ENTER_YOUR_PREFIX/’
Get the list of objects by passing bucket name and prefix.
response = s3_client.list_objects_v2(Bucket=BUCKET, Prefix=PREFIX)
According to my requirement, I need the file that ends with “.json”. So filter only the required objects.
if ‘Contents’ in response:
for object in response[‘Contents’]:
if ‘.json’ in object[‘Key’]:
print(‘Reuploading’, object[‘Key’])
Now inside this for and if loop we have to read the object and upload it. Using the get_object function, get the file and re-upload it using the put_object function by passing bucket name and key.
print(‘Reuploading’, object[‘Key’])
s3Object = s3_client.get_object(Bucket=BUCKET, Key=object[‘Key’])
s3_client.put_object(Body=s3Object[‘Body’].read(),Bucket=BUCKET, Key=object[‘Key’])
And this is how the final steps code looks like.
import boto3
s3_client = boto3.client(‘s3’)
BUCKET = ‘ENTER_YOUR_BUCKET_NAME’
PREFIX = ‘ENTER_YOUR_PREFIX/’
def lambda_handler(event, context):
response = s3_client.list_objects_v2(Bucket=BUCKET, Prefix=PREFIX)
if ‘Contents’ in response:
for object in response[‘Contents’]:
if ‘.json’ in object[‘Key’]:
print(‘Reuploading’, object[‘Key’])
s3Object = s3_client.get_object(Bucket=BUCKET, Key=object[‘Key’])
s3_client.put_object(Body=s3Object[‘Body’].read(),Bucket=BUCKET, Key=object[‘Key’])
Happy Programming!!