How to Replace Files in S3 Using Python
A concise guide to safely replacing files in Amazon S3 using boto3 — covering atomic replacement, versioning, metadata preservation, and common edge cases.
Replacing a file in S3 sounds trivial. It's not — especially when you need to preserve metadata, handle versioning correctly, and avoid race conditions.
The Simple Case
import boto3
s3 = boto3.client('s3')
def replace_s3_file(bucket: str, key: str, new_content: bytes, content_type: str) -> None:
s3.put_object(
Bucket=bucket,
Key=key,
Body=new_content,
ContentType=content_type,
)S3 put_object is atomic — readers will see either the old object or the new one, never a partial write.
Preserving Metadata
If the original object has custom metadata you want to keep:
existing = s3.get_object(Bucket=bucket, Key=key)
old_metadata = existing['Metadata']
s3.put_object(
Bucket=bucket,
Key=key,
Body=new_content,
ContentType=content_type,
Metadata=old_metadata,
)With Versioning Enabled
When versioning is enabled, put_object creates a new version. The old version is preserved. To clean up old versions automatically, configure S3 Lifecycle rules.
Safe Replace with Backup
For critical files, copy the original to a backup key before replacing:
s3.copy_object(
Bucket=bucket,
CopySource={'Bucket': bucket, 'Key': key},
Key=f'{key}.bak.{int(time.time())}',
)Read the full guide with edge cases and error handling on Medium.
Need a team that can actually ship this?
NexForge combines AI development, product engineering, cloud delivery, and startup execution so ideas turn into production systems.
