s3path

0.6.5 · active · verified Thu Apr 09

s3path offers a Pythonic, object-oriented interface for working with AWS S3 objects and directories, mirroring the standard library's `pathlib` module. It seamlessly integrates with `boto3` to provide a convenient filesystem-like experience for S3 buckets. The current version is 0.6.5, with consistent updates and patch releases.

Warnings

Install

Imports

Quickstart

This example demonstrates how to initialize `S3Path`, configure the underlying `boto3` session using environment variables, write text to an S3 object, read its content, and list objects within an S3 prefix using `iterdir()`.

import os
import boto3
from s3path import S3Path

# Configure boto3 session (recommended for programmatic access)
# Replace with your actual region and credentials or profile
# For local testing, ensure AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY are set
boto3.setup_default_session(
    region_name=os.environ.get('AWS_REGION', 'us-east-1'),
    aws_access_key_id=os.environ.get('AWS_ACCESS_KEY_ID', 'test'),
    aws_secret_access_key=os.environ.get('AWS_SECRET_ACCESS_KEY', 'test')
)

bucket_name = 'your-s3-bucket'
file_key = 'my-folder/my-file.txt'

# Create an S3Path object
s3_path = S3Path(f'/{bucket_name}/{file_key}')
print(f"S3 Path: {s3_path}")

# Check if the file exists (requires S3 interaction)
if not s3_path.exists():
    print(f"Creating file: {s3_path}")
    s3_path.write_text('Hello from s3path!')
    print("File created.")
else:
    print(f"File '{s3_path}' already exists.")

# Read content
content = s3_path.read_text()
print(f"Content of '{s3_path}': {content}")

# List contents of a directory-like prefix
directory_path = S3Path(f'/{bucket_name}/my-folder/')
print(f"\nListing contents of '{directory_path}':")
for p in directory_path.iterdir():
    print(f" - {p}")

# Clean up (optional)
# s3_path.unlink() # Uncomment to delete the file
# print(f"Deleted {s3_path}")

view raw JSON →