put_object

Upload files to AWS S3 using Python

Put Object

This Python script demonstrates how to upload a file to an Amazon S3 bucket using the put_object method from the boto3 library. The put_object function is essential for storing objects in S3, which is a common task in cloud storage and application development. Ensure you have the boto3 library installed and your AWS credentials configured before running this script.

import boto3

# Create an S3 client
s3 = boto3.client('s3')

# Upload a file
with open('file.txt', 'r') as file_content:
    s3.put_object(Bucket='my-bucket-name', Key='testfolder/file.txt', Body=file_content.read())

Explanation

The script starts by importing the boto3 library, which is the AWS SDK for Python. It then creates an S3 client, which allows you to interact with the S3 service. The put_object method is used to upload the file to the specified bucket and key. The Bucket parameter specifies the name of the S3 bucket, and the Key parameter specifies the path and name of the object in the bucket. The Body parameter contains the content of the file to be uploaded.

Prerequisites

  • AWS account
  • AWS CLI configured with appropriate credentials
  • boto3 library installed (pip install boto3)

Additional Resources