0
0
AwsHow-ToBeginner · 3 min read

How to Delete a File from AWS S3 Bucket Easily

To delete a file from an AWS S3 bucket, use the aws s3 rm s3://bucket-name/file-key command in AWS CLI or call the DeleteObject method in AWS SDKs. This removes the specified file permanently from the bucket.
📐

Syntax

The basic syntax to delete a file from S3 using AWS CLI is:

  • aws s3 rm s3://bucket-name/file-key: Deletes the file identified by file-key in the specified bucket-name.
  • In AWS SDKs, use the DeleteObject method with parameters for bucket name and file key.
bash
aws s3 rm s3://my-bucket/my-folder/my-file.txt
Output
delete: s3://my-bucket/my-folder/my-file.txt
💻

Example

This example shows how to delete a file named example.txt from an S3 bucket called my-sample-bucket using Python AWS SDK (boto3).

python
import boto3

s3 = boto3.client('s3')

bucket_name = 'my-sample-bucket'
file_key = 'example.txt'

response = s3.delete_object(Bucket=bucket_name, Key=file_key)
print('Delete response:', response)
Output
Delete response: {'ResponseMetadata': {'RequestId': 'XXXXXXXXXXXX', 'HostId': 'YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY', 'HTTPStatusCode': 204, 'HTTPHeaders': {...}, 'RetryAttempts': 0}}
⚠️

Common Pitfalls

  • Trying to delete a file that does not exist will not cause an error but returns a success response.
  • Incorrect bucket name or file key will fail silently or with an error.
  • Not having proper permissions (IAM policies) to delete objects will cause access denied errors.
  • Using the wrong region or endpoint can cause failures.
python
## Wrong way: Missing permissions
import boto3
s3 = boto3.client('s3')
try:
    s3.delete_object(Bucket='wrong-bucket', Key='file.txt')
except Exception as e:
    print('Error:', e)

## Right way: Ensure correct bucket and permissions
s3.delete_object(Bucket='correct-bucket', Key='file.txt')
Output
Error: An error occurred (AccessDenied) when calling the DeleteObject operation: Access Denied
📊

Quick Reference

Here is a quick cheat-sheet for deleting files from S3:

ActionCommand / MethodNotes
Delete file via CLIaws s3 rm s3://bucket-name/file-keySimple and fast from terminal
Delete file via Python SDKs3.delete_object(Bucket='bucket', Key='file')Use boto3 client in Python
Check permissionsIAM policy with s3:DeleteObjectRequired to delete files
Verify file keyExact path and filenameMust match file to delete

Key Takeaways

Use the AWS CLI command 'aws s3 rm' or SDK method 'DeleteObject' to delete files from S3.
Ensure you have correct bucket name, file key, and permissions to avoid errors.
Deleting a non-existent file does not cause an error but no file is removed.
Always verify your AWS region and credentials before deleting files.
Use IAM policies to control who can delete files in your S3 buckets.