To use AWS S3 with Python, you will need to install the boto3 library, which allows you to interact with the S3 service through Python code. Here is an example of how you can use boto3 to upload a file to an S3 bucket:
import boto3
# Create an S3 client
s3 = boto3.client(‘s3’)
# Set the name of the bucket and the file you want to upload
bucket_name = ‘my-bucket’
file_name = ‘path/to/my-file.txt’
# Upload the file to the bucket
s3.upload_file(file_name, bucket_name, file_name)
This example uses the upload_file
method of the S3 client to upload the file to the specified bucket. You can also use other methods of the S3 client, such as download_file
and list_objects
to download files and list the contents of a bucket, respectively.
You must have valid AWS access key and secret key to connect your python to AWS S3. You can find them in your AWS IAM user. You can also use the boto3.resource
method to create a higher-level, resource-oriented interface to S3.
s3 = boto3.resource(‘s3’)
# Set the name of the bucket and the file you want to upload
bucket_name = ‘my-bucket’
file_name = ‘path/to/my-file.txt’
# Create a boto3 resource for the S3 bucket
bucket = s3.Bucket(bucket_name)
# Upload the file to the bucket
bucket.upload_file(file_name, file_name)
Note that, you can also configure your AWS access and secret key in ~/.aws/credentials
file or set them as enviroment variables.