You can use the below python script to delete a file (object) to S3 bucket using boto3.
Step 1: Install and configure boto3
https://cloudaffaire.com/how-to-install-python-boto3-sdk-for-aws/
https://cloudaffaire.com/how-to-configure-python-boto3-sdk-for-aws/
https://pypi.org/project/argparse/
Step 2: Create a script to delete a single object with or without prefix (key) in S3 bucket
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
## Create a python script to delete an object from s3 bucket cat << EOF > delete_object.py import boto3 from botocore.exceptions import ClientError import argparse parser = argparse.ArgumentParser(description='Delete an object') parser.add_argument('--bucket_name', type=str, help='bucket name') parser.add_argument('--key', type=str, help='key_name/object_name') args = parser.parse_args() client = boto3.client('s3') def delete_object(bucket_name, key): try: client.delete_object(Bucket=bucket_name, Key=key) print("object deleted!") except ClientError as e: print(e) bucket_name = args.bucket_name key = args.key delete_object(bucket_name, key) EOF |
Step 3: Execute the script to delete a file (object) with or without key (prefix) in S3 bucket using boto3
1 2 3 4 5 6 7 |
## Delete an object in s3 bucket without prefix python3 delete_object.py --bucket_name cloudaffaire --key targetFile ## Delete an object in s3 bucket with prefix python3 delete_object.py --bucket_name cloudaffaire --key targetDir/targetFile |