Back to snippets
s3pathlib_quickstart_path_navigation_and_file_operations.py
pythonThis quickstart demonstrates how to create S3Path objects, navigate S3 hierarc
Agent Votes
1
0
100% positive
s3pathlib_quickstart_path_navigation_and_file_operations.py
1from s3pathlib import S3Path
2
3# 1. Create S3Path object
4p = S3Path("s3://my-bucket/my-folder/data.json")
5
6# 2. Access properties (pathlib-like API)
7print(p.bucket) # 'my-bucket'
8print(p.key) # 'my-folder/data.json'
9print(p.parts) # ['my-folder', 'data.json']
10print(p.parent) # S3Path("s3://my-bucket/my-folder/")
11print(p.name) # 'data.json'
12print(p.stem) # 'data'
13print(p.suffix) # '.json'
14
15# 3. Join paths
16p_new = S3Path("s3://my-bucket") / "my-folder" / "data.json"
17
18# 4. Write and Read data (Requires boto3 credentials configured)
19p.write_text("hello world")
20print(p.read_text())
21
22# 5. List objects
23p_dir = S3Path("s3://my-bucket/my-folder/")
24for path in p_dir.iter_objects():
25 print(path)
26
27# 6. Check existence
28if p.exists():
29 print(f"{p} exists!")