import boto3
import os
# Connect to S3
s3 = boto3.client('s3')
# Set the name of the S3 bucket and local directory
bucket_name = 'your-bucket-name'
local_directory = 'path/to/local/directory'
# Get a list of all the S3 objects in the bucket
objects = s3.list_objects(Bucket=bucket_name)['Contents']
# Iterate through the S3 objects
for obj in objects:
# Get the file name
file_name = obj['Key']
# Check if the file exists in the local directory
local_file = os.path.join(local_directory, file_name)
if not os.path.exists(local_file):
# If the file does not exist, download it from S3
s3.download_file(bucket_name, file_name, local_file)
else:
# If the file exists, compare the S3 object and the local file
s3_object = s3.get_object(Bucket=bucket_name, Key=file_name)
if s3_object['ContentLength'] != os.path.getsize(local_file):
# If the sizes are different, download the file from S3
s3.download_file(bucket_name, file_name, local_file)
# Get a list of all the files in the local directory
local_files = os.listdir(local_directory)
# Iterate through the local files
for file_name in local_files:
# Check if the file exists in S3
s3_object = s3.list_objects(Bucket=bucket_name, Prefix=file_name)
if not s3_object.get('Contents'):
# If the file does not exist, upload it to S3
local_file = os.path.join(local_directory, file_name)
s3.upload_file(local_file, bucket_name, file_name)
This script uses the boto3 library to interact with Amazon S3. It first gets a list of all the S3 objects in the specified bucket and iterates through them. If a file does not exist in the local directory, it is downloaded from S3. If the file exists, but the sizes are different, the file is also downloaded from S3. The script then gets a list of all the files in the local directory and iterates through them. If a file does not exist in S3, it is uploaded to S3.