0
# Core Path Operations
1
2
Essential pathlib-compatible operations for working with cloud storage paths. These operations provide the foundation for path construction, manipulation, and basic filesystem interactions that work consistently across all supported cloud providers.
3
4
## Capabilities
5
6
### Path Construction
7
8
Create and manipulate cloud paths using familiar pathlib syntax.
9
10
```python { .api }
11
class CloudPath:
12
def __init__(self, cloud_path: str, *parts: str, client=None):
13
"""
14
Create a new CloudPath instance.
15
16
Args:
17
cloud_path: Cloud storage URI (e.g., "s3://bucket/path")
18
*parts: Additional path segments to join
19
client: Optional client instance for cloud operations
20
"""
21
22
@classmethod
23
def from_uri(cls, uri: str) -> "CloudPath":
24
"""Create CloudPath instance from URI string."""
25
26
@classmethod
27
def is_valid_cloudpath(cls, path: str, raise_on_error: bool = False) -> bool:
28
"""
29
Validate if path is a valid cloud path.
30
31
Args:
32
path: Path string to validate
33
raise_on_error: Raise exception on invalid path
34
35
Returns:
36
True if valid cloud path
37
"""
38
```
39
40
### Path Properties
41
42
Access path components and metadata using pathlib-style properties.
43
44
```python { .api }
45
@property
46
def name(self) -> str:
47
"""Final path component (filename)."""
48
49
@property
50
def stem(self) -> str:
51
"""Final path component without suffix."""
52
53
@property
54
def suffix(self) -> str:
55
"""File extension including the dot."""
56
57
@property
58
def suffixes(self) -> list[str]:
59
"""List of all file extensions."""
60
61
@property
62
def parent(self) -> "CloudPath":
63
"""Parent directory path."""
64
65
@property
66
def parents(self) -> "CloudPath.parents":
67
"""Sequence of parent paths."""
68
69
@property
70
def parts(self) -> tuple[str, ...]:
71
"""Tuple of path components."""
72
73
@property
74
def anchor(self) -> str:
75
"""Cloud prefix (e.g., "s3://")."""
76
77
@property
78
def drive(self) -> str:
79
"""Drive name (bucket/container name)."""
80
```
81
82
### Path Manipulation
83
84
Modify and combine paths using standard pathlib operations.
85
86
```python { .api }
87
def __truediv__(self, other: str) -> "CloudPath":
88
"""Join paths using / operator."""
89
90
def joinpath(self, *pathsegments: str) -> "CloudPath":
91
"""
92
Join path segments.
93
94
Args:
95
*pathsegments: Path segments to join
96
97
Returns:
98
New CloudPath with joined segments
99
"""
100
101
def with_name(self, name: str) -> "CloudPath":
102
"""
103
Return new path with different filename.
104
105
Args:
106
name: New filename
107
108
Returns:
109
New CloudPath with replaced filename
110
"""
111
112
def with_suffix(self, suffix: str) -> "CloudPath":
113
"""
114
Return new path with different suffix.
115
116
Args:
117
suffix: New file extension (including dot)
118
119
Returns:
120
New CloudPath with replaced suffix
121
"""
122
123
def with_stem(self, stem: str) -> "CloudPath":
124
"""
125
Return new path with different stem.
126
127
Args:
128
stem: New filename without extension
129
130
Returns:
131
New CloudPath with replaced stem
132
"""
133
134
def with_segments(self, *pathsegments: str) -> "CloudPath":
135
"""
136
Create new path from segments.
137
138
Args:
139
*pathsegments: Path segments for new path
140
141
Returns:
142
New CloudPath constructed from segments
143
"""
144
```
145
146
### Path Resolution
147
148
Resolve and normalize paths (note: most operations are no-ops for cloud paths).
149
150
```python { .api }
151
def absolute(self) -> "CloudPath":
152
"""Return absolute path (no-op for cloud paths)."""
153
154
def resolve(self, strict: bool = False) -> "CloudPath":
155
"""Resolve path (no-op for cloud paths)."""
156
157
def relative_to(self, other: typing.Union[str, "CloudPath"]) -> "CloudPath":
158
"""
159
Return relative path from other path.
160
161
Args:
162
other: Base path for relative calculation
163
164
Returns:
165
Relative path from other to self
166
"""
167
168
def is_relative_to(self, other: typing.Union[str, "CloudPath"]) -> bool:
169
"""
170
Check if path is relative to other path.
171
172
Args:
173
other: Base path to check against
174
175
Returns:
176
True if path is under other path
177
"""
178
```
179
180
### Path Validation
181
182
Validate and check path properties.
183
184
```python { .api }
185
@classmethod
186
def validate(cls, v):
187
"""Pydantic validator for CloudPath instances."""
188
189
def __str__(self) -> str:
190
"""String representation of the path."""
191
192
def __repr__(self) -> str:
193
"""Detailed string representation."""
194
195
def __hash__(self) -> int:
196
"""Hash value for use in sets and dicts."""
197
198
def __eq__(self, other) -> bool:
199
"""Equality comparison."""
200
201
def __lt__(self, other) -> bool:
202
"""Less than comparison for sorting."""
203
204
def __fspath__(self) -> str:
205
"""
206
Return path for os.fspath() compatibility.
207
Returns local cached path if available.
208
"""
209
```
210
211
## Usage Examples
212
213
### Basic Path Operations
214
215
```python
216
from cloudpathlib import CloudPath
217
218
# Create path
219
path = CloudPath("s3://my-bucket/data/file.txt")
220
221
# Access components
222
print(path.name) # "file.txt"
223
print(path.stem) # "file"
224
print(path.suffix) # ".txt"
225
print(path.parent) # S3Path('s3://my-bucket/data/')
226
print(path.parts) # ('s3://my-bucket', 'data', 'file.txt')
227
228
# Path manipulation
229
new_path = path.with_suffix('.json') # s3://my-bucket/data/file.json
230
parent_dir = path.parent # s3://my-bucket/data/
231
sibling = path.parent / "other.txt" # s3://my-bucket/data/other.txt
232
```
233
234
### Path Construction and Joining
235
236
```python
237
# Multiple ways to construct paths
238
path1 = CloudPath("s3://bucket", "folder", "file.txt")
239
path2 = CloudPath("s3://bucket") / "folder" / "file.txt"
240
path3 = CloudPath("s3://bucket").joinpath("folder", "file.txt")
241
242
# All result in: S3Path('s3://bucket/folder/file.txt')
243
assert path1 == path2 == path3
244
```
245
246
### Path Validation
247
248
```python
249
# Check if string is valid cloud path
250
CloudPath.is_valid_cloudpath("s3://bucket/file.txt") # True
251
CloudPath.is_valid_cloudpath("/local/path") # False
252
CloudPath.is_valid_cloudpath("not-a-path") # False
253
254
# Validation with error handling
255
try:
256
CloudPath.is_valid_cloudpath("invalid://path", raise_on_error=True)
257
except InvalidPrefixError:
258
print("Invalid cloud path prefix")
259
```
260
261
### Working with Path Hierarchies
262
263
```python
264
path = CloudPath("s3://bucket/level1/level2/level3/file.txt")
265
266
# Navigate up the hierarchy
267
print(path.parent) # s3://bucket/level1/level2/level3/
268
print(path.parent.parent) # s3://bucket/level1/level2/
269
print(list(path.parents)) # All parent paths
270
271
# Check relationships
272
base = CloudPath("s3://bucket/level1")
273
print(path.is_relative_to(base)) # True
274
print(path.relative_to(base)) # level2/level3/file.txt
275
```