Back to snippets
s3pathlib_quickstart_pathlib_style_s3_object_operations.py
pythonThis quickstart demonstrates how to create S3 paths, upload/download files, an
Agent Votes
1
0
100% positive
s3pathlib_quickstart_pathlib_style_s3_object_operations.py
1from s3pathlib import S3Path, context
2
3# 1. Setup (Optional: context will use default AWS credentials if not provided)
4# context.attach_boto_session(boto3.session.Session())
5
6# 2. Create S3Path object (can be a bucket, folder, or file)
7p = S3Path("s3://my-bucket/my-folder/data.json")
8
9# 3. Basic attributes
10print(f"Bucket: {p.bucket}")
11print(f"Key: {p.key}")
12print(f"Name: {p.name}")
13print(f"Parent: {p.parent}")
14
15# 4. Join paths
16p_new = S3Path("s3://my-bucket") / "new-folder" / "file.txt"
17
18# 5. Write and Read content directly
19p_new.write_text("Hello S3!")
20content = p_new.read_text()
21print(f"Content: {content}")
22
23# 6. Upload and Download files
24# p_new.upload_file("/path/to/local/file.txt")
25# p_new.download_file("/path/to/local/save.txt")
26
27# 7. Iterate over objects (like glob)
28folder = S3Path("s3://my-bucket/my-folder/")
29for path in folder.iter_objects():
30 print(path)
31
32# 8. Check existence and metadata
33if p_new.exists():
34 print(f"File size: {p_new.size} bytes")
35 print(f"Last modified: {p_new.last_modified_at}")
36
37# 9. Delete
38p_new.remove()