Deleting Files from S3 Bucket in Python

  • Last updated Apr 25, 2024

Follow these steps to delete files from an Amazon S3 bucket using the AWS Boto3 library in Python:

  1. Install Boto3 library:
  2. pip install boto3
  3. Here's a sample Python code to delete files from an amazon S3 bucket:
  4. import boto3
    from botocore.exceptions import ClientError
    
    ACCESS_SECRET = "your aws access secret"
    ACCESS_KEY = "your aws access key"
    
    s3_client = boto3.client('s3', region_name='us-east-1', aws_access_key_id=ACCESS_KEY,
                             aws_secret_access_key=ACCESS_SECRET)
    
    bucket_name = "bucket-one"
    
    # filename
    file_name = "example.txt"
    
    # location of the file to delete in S3 bucket
    key = "folder/"+file_name
    
    # deleting file
    try:
        s3_client.delete_object(Bucket=bucket_name, Key=key)
    except ClientError as ex:
        print("Error: ", ex)