Path Manipulation¶
Everything in this chapter works on the path alone and never calls AWS, so it runs without credentials: build a path, read its parts, join, change, make relative paths, compare, sort and serialize.
[1]:
from s3pathlib.api import S3Path
1. Build a path¶
S3Path(bucket, *parts). The first argument is the bucket, the others are parts of the key:
[2]:
S3Path("my-bucket", "folder", "file.txt")
[2]:
S3Path('s3://my-bucket/folder/file.txt')
The first argument can also hold the whole path, as bucket/key, an S3 URI or an S3 ARN:
[3]:
S3Path("my-bucket/folder/file.txt")
[3]:
S3Path('s3://my-bucket/folder/file.txt')
[4]:
S3Path("s3://my-bucket/folder/file.txt")
[4]:
S3Path('s3://my-bucket/folder/file.txt')
[5]:
S3Path("arn:aws:s3:::my-bucket/folder/file.txt")
[5]:
S3Path('s3://my-bucket/folder/file.txt')
Repeated / are collapsed and empty parts are ignored:
[6]:
S3Path("my-bucket", "folder//sub/", "", "file.txt")
[6]:
S3Path('s3://my-bucket/folder/sub/file.txt')
The last non-empty part decides the type: a trailing / makes a folder (a “dir”), otherwise it is a file.
[7]:
S3Path("my-bucket", "folder", "data")
[7]:
S3Path('s3://my-bucket/folder/data')
[8]:
S3Path("my-bucket", "folder", "data/")
[8]:
S3Path('s3://my-bucket/folder/data/')
from_s3_uri and from_s3_arn accept only that format, which is useful when the input comes from users:
[9]:
S3Path.from_s3_uri("s3://my-bucket/folder/")
[9]:
S3Path('s3://my-bucket/folder/')
[10]:
S3Path.from_s3_arn("arn:aws-cn:s3:::my-bucket/folder/file.txt")
[10]:
S3Path('s3://my-bucket/folder/file.txt')
[11]:
from s3pathlib.api import exc
try:
S3Path.from_s3_uri("my-bucket/folder/")
except exc.S3ValidationError as e:
print(f"{type(e).__name__}: {e}")
S3ValidationError: S3 URI must start with 's3://', got 'my-bucket/folder/'
The constructor rejects what is clearly not an S3 path, such as an HTTPS URL:
[12]:
try:
S3Path("https://my-bucket.s3.amazonaws.com/file.txt")
except exc.S3ValidationError as e:
print(f"{type(e).__name__}: {e}")
S3ValidationError: bucket 'https:' in 'https://my-bucket.s3.amazonaws.com/file.txt' contains ':', which is not allowed in any bucket name
It checks the format, not the bucket naming rules: S3 is the authority on names, and old buckets may break today’s rules. Use validate_s3_bucket to check a name yourself:
[13]:
from s3pathlib.api import validate_s3_bucket
try:
validate_s3_bucket("My_Bucket")
except exc.S3ValidationError as e:
print(f"{type(e).__name__}: {e}")
S3ValidationError: Bucket names can consist only of lowercase letters, numbers, dots (.), and hyphens (-). invalid char found ['B', 'M', '_']
validate_s3_key, validate_s3_uri and validate_s3_arn check the other parts the same way.
2. The six kinds of path¶
Every S3Path is one of six kinds. The three with a bucket are absolute: a file (an S3 object), a dir (a logical folder) and the bucket itself (the root dir).
[14]:
file = S3Path("my-bucket", "folder", "file.txt")
file
[14]:
S3Path('s3://my-bucket/folder/file.txt')
[15]:
folder = S3Path("my-bucket", "folder/")
folder
[15]:
S3Path('s3://my-bucket/folder/')
[16]:
bucket = S3Path("my-bucket")
bucket
[16]:
S3Path('s3://my-bucket/')
The three without a bucket are relative: a relative file, a relative dir, and the void path, the empty relative path. S3Path.make_relpath builds a relative path, and S3Path() is void:
[17]:
relpath_file = S3Path.make_relpath("folder", "file.txt")
relpath_file
[17]:
S3RelPath('folder/file.txt')
[18]:
relpath_dir = S3Path.make_relpath("folder/")
relpath_dir
[18]:
S3RelPath('folder/')
[19]:
void = S3Path()
void
[19]:
S3VoidPath()
The is_* methods tell them apart. A bucket is also a dir:
[20]:
paths = [file, folder, bucket, relpath_file, relpath_dir, void]
for p in paths:
print(p, "is_file:", p.is_file(), "is_dir:", p.is_dir(), "is_bucket:", p.is_bucket())
S3Path('s3://my-bucket/folder/file.txt') is_file: True is_dir: False is_bucket: False
S3Path('s3://my-bucket/folder/') is_file: False is_dir: True is_bucket: False
S3Path('s3://my-bucket/') is_file: False is_dir: True is_bucket: True
S3RelPath('folder/file.txt') is_file: True is_dir: False is_bucket: False
S3RelPath('folder/') is_file: False is_dir: True is_bucket: False
S3VoidPath() is_file: False is_dir: False is_bucket: False
Void is also a relative path:
[21]:
for p in paths:
print(p, "is_relpath:", p.is_relpath(), "is_void:", p.is_void())
S3Path('s3://my-bucket/folder/file.txt') is_relpath: False is_void: False
S3Path('s3://my-bucket/folder/') is_relpath: False is_void: False
S3Path('s3://my-bucket/') is_relpath: False is_void: False
S3RelPath('folder/file.txt') is_relpath: True is_void: False
S3RelPath('folder/') is_relpath: True is_void: False
S3VoidPath() is_relpath: True is_void: True
A relative path has a key but no bucket, so its uri is None. The key of a bucket and of void is "", the same as Prefix="" in the S3 API.
[22]:
for p in paths:
print(p, "bucket:", repr(p.bucket), "key:", repr(p.key), "uri:", repr(p.uri))
S3Path('s3://my-bucket/folder/file.txt') bucket: 'my-bucket' key: 'folder/file.txt' uri: 's3://my-bucket/folder/file.txt'
S3Path('s3://my-bucket/folder/') bucket: 'my-bucket' key: 'folder/' uri: 's3://my-bucket/folder/'
S3Path('s3://my-bucket/') bucket: 'my-bucket' key: '' uri: 's3://my-bucket/'
S3RelPath('folder/file.txt') bucket: None key: 'folder/file.txt' uri: None
S3RelPath('folder/') bucket: None key: 'folder/' uri: None
S3VoidPath() bucket: None key: '' uri: None
The ensure_* methods check the kind and raise an exception of s3pathlib.exc, handy at the top of your own functions. A check that passes returns None:
[23]:
file.ensure_file()
[24]:
try:
file.ensure_dir()
except exc.S3PathIsNotFolderError as e:
print(f"{type(e).__name__}: {e}")
S3PathIsNotFolderError: 's3://my-bucket/folder/file.txt' is not a dir!
There are ensure_file, ensure_not_file, ensure_dir, ensure_not_dir, ensure_bucket, ensure_relpath and ensure_not_relpath (ensure_object / ensure_not_object are aliases of the file ones). Each exception of s3pathlib.exc also inherits a builtin one, so a generic except still works: S3PathIsNotRelpathError is a TypeError.
[25]:
try:
bucket.ensure_relpath()
except TypeError as e:
print(f"{type(e).__name__}: {e}")
S3PathIsNotRelpathError: 's3://my-bucket/' is not a relpath!
3. Attributes¶
The name parts follow pathlib: basename is name, fname is stem, ext is suffix.
[26]:
p = S3Path("my-bucket", "data", "2024", "report.tar.gz")
print(f"{p.parts = }")
p.parts = ['data', '2024', 'report.tar.gz']
[27]:
print(f"{p.basename = }")
p.basename = 'report.tar.gz'
[28]:
print(f"{p.fname = }")
p.fname = 'report.tar'
[29]:
print(f"{p.ext = }")
p.ext = '.gz'
dirname is the name of the parent folder:
[30]:
print(f"{p.dirname = }")
p.dirname = '2024'
abspath and dirpath are the Unix style paths from the bucket, which works like a drive; root is the bucket.
[31]:
print(f"{p.abspath = }")
p.abspath = '/data/2024/report.tar.gz'
[32]:
print(f"{p.dirpath = }")
p.dirpath = '/data/2024/'
[33]:
print(f"{p.root = }")
p.root = S3Path('s3://my-bucket/')
parent is always a dir:
[34]:
p.parent
[34]:
S3Path('s3://my-bucket/data/2024/')
parents goes up to the bucket, like pathlib.PurePath.parents:
[35]:
for parent in p.parents:
print(parent)
S3Path('s3://my-bucket/data/2024/')
S3Path('s3://my-bucket/data/')
S3Path('s3://my-bucket/')
For a relative path, parents ends with void:
[36]:
for parent in S3Path.make_relpath("a/b/c.txt").parents:
print(parent)
S3RelPath('a/b/')
S3RelPath('a/')
S3VoidPath()
A folder’s basename is the folder name:
[37]:
folder = S3Path("my-bucket", "data", "2024/")
print(f"{folder.basename = }")
folder.basename = '2024'
A folder has no file name and no extension, so fname and ext raise:
[38]:
try:
folder.ext
except exc.S3PathIsNotFileError as e:
print(f"{type(e).__name__}: {e}")
S3PathIsNotFileError: 's3://my-bucket/data/2024/' is not a file, it has no ext!
arn and console_url use the commercial aws partition:
[39]:
p = S3Path("my-bucket", "folder", "file.txt")
print(f"{p.arn = }")
p.arn = 'arn:aws:s3:::my-bucket/folder/file.txt'
[40]:
print(f"{p.console_url = }")
p.console_url = 'https://console.aws.amazon.com/s3/object/my-bucket?prefix=folder/file.txt'
get_arn and get_console_url take another partition (aws-cn, aws-us-gov, aws-eusc) or a region:
[41]:
p.get_arn("aws-us-gov")
[41]:
'arn:aws-us-gov:s3:::my-bucket/folder/file.txt'
AwsPartitionEnum has the partition names:
[42]:
from s3pathlib.api import AwsPartitionEnum
p.get_arn(AwsPartitionEnum.aws_cn)
[42]:
'arn:aws-cn:s3:::my-bucket/folder/file.txt'
[43]:
p.get_console_url(region="us-west-2")
[43]:
'https://us-west-2.console.aws.amazon.com/s3/object/my-bucket?region=us-west-2&prefix=folder/file.txt'
[44]:
p.get_console_url(partition="aws-cn")
[44]:
'https://console.amazonaws.cn/s3/object/my-bucket?prefix=folder/file.txt'
4. Join¶
/ puts a part under a dir:
[45]:
S3Path("my-bucket") / "folder/" / "file.txt"
[45]:
S3Path('s3://my-bucket/folder/file.txt')
joinpath joins several parts at once:
[46]:
S3Path("my-bucket").joinpath("folder", "file.txt")
[46]:
S3Path('s3://my-bucket/folder/file.txt')
So does a list on the right side of /:
[47]:
S3Path("my-bucket") / ["folder", "file.txt"]
[47]:
S3Path('s3://my-bucket/folder/file.txt')
A relative path can be joined too, which is how you rebuild a path under another folder:
[48]:
relpath = S3Path.make_relpath("2024/", "report.csv")
S3Path("my-bucket", "data/") / relpath
[48]:
S3Path('s3://my-bucket/data/2024/report.csv')
Joining onto a file is deprecated. In S3Path("my-bucket") / "folder" / "file.txt", the middle result S3Path("my-bucket") / "folder" is a file, because it has no trailing /. A file has no sub path, so this emits a DeprecationWarning today and will raise S3PathIsNotFolderError in 4.0.0. Write "folder/", call .to_dir(), or join all parts at once as above.
The cell below catches the warning to show its message:
[49]:
import warnings
with warnings.catch_warnings(record=True) as records:
warnings.simplefilter("always")
S3Path("my-bucket") / "folder" / "file.txt"
print(records[0].message)
's3://my-bucket/folder' is a file. Joining onto a file is deprecated since 3.0.0, and will raise S3PathIsNotFolderError in 4.0.0. Join onto a dir instead: end the folder with '/' (e.g. ... / "folder/" / "file.txt"), call .to_dir() first, or join all parts at once (e.g. .joinpath("folder", "file.txt")).
5. Change a path¶
A path never changes; these methods return a new one. change replaces some attributes and keeps the others.
[50]:
p = S3Path("my-bucket", "data", "2024", "report.csv")
p.change(new_bucket="other-bucket")
[50]:
S3Path('s3://other-bucket/data/2024/report.csv')
[51]:
p.change(new_ext=".json")
[51]:
S3Path('s3://my-bucket/data/2024/report.json')
[52]:
p.change(new_fname="summary")
[52]:
S3Path('s3://my-bucket/data/2024/summary.csv')
[53]:
p.change(new_basename="2024-12.csv")
[53]:
S3Path('s3://my-bucket/data/2024/2024-12.csv')
[54]:
p.change(new_dirname="2025")
[54]:
S3Path('s3://my-bucket/data/2025/report.csv')
[55]:
p.change(new_dirpath="archive/2024/")
[55]:
S3Path('s3://my-bucket/archive/2024/report.csv')
[56]:
p.change(new_bucket="other-bucket", new_abspath="new/key.csv")
[56]:
S3Path('s3://other-bucket/new/key.csv')
new_basename can turn a file into a folder (end it with /):
[57]:
p.change(new_basename="report/")
[57]:
S3Path('s3://my-bucket/data/2024/report/')
Arguments that conflict or do not fit the path raise ValueError:
[58]:
try:
p.change(new_ext="json")
except ValueError as e:
print(f"{type(e).__name__}: {e}")
ValueError: new_ext has to be empty, or '.' followed by the extension, got 'json'
[59]:
try:
p.change(new_dirpath="a/", new_dirname="b")
except ValueError as e:
print(f"{type(e).__name__}: {e}")
ValueError: pass new_dirpath or new_dirname, not both
to_dir and to_file switch the type:
[60]:
S3Path("my-bucket", "data").to_dir()
[60]:
S3Path('s3://my-bucket/data/')
[61]:
S3Path("my-bucket", "data/").to_file()
[61]:
S3Path('s3://my-bucket/data')
copy returns an equal path (without the metadata loaded from S3, see Metadata and Tags):
[62]:
p.copy() == p
[62]:
True
6. Relative paths¶
relative_to gives the path of p under a folder base:
[63]:
base = S3Path("my-bucket", "data/")
p = S3Path("my-bucket", "data", "2024", "report.csv")
relpath = p.relative_to(base)
relpath
[63]:
S3RelPath('2024/report.csv')
It is the inverse of /: joining the relative path back onto base gives p again.
[64]:
base / relpath == p
[64]:
True
This is how you mirror a folder somewhere else:
[65]:
S3Path("other-bucket", "backup/") / relpath
[65]:
S3Path('s3://other-bucket/backup/2024/report.csv')
p - base is a short way to write p.relative_to(base):
[66]:
p - base
[66]:
S3RelPath('2024/report.csv')
When p is not under base, there is no relative path, and it raises ValueError:
[67]:
try:
p.relative_to(S3Path("my-bucket", "logs/"))
except ValueError as e:
print(f"{type(e).__name__}: {e}")
ValueError: 's3://my-bucket/data/2024/report.csv' is not under 's3://my-bucket/logs/'
The base should be a dir. A file as the base (S3Path("my-bucket", "data"), without /) works for now with a DeprecationWarning, and raises S3PathIsNotFolderError in 4.0.0, for the same reason as joining onto a file.
is_parent_of tests the folder hierarchy:
[68]:
data = S3Path("my-bucket", "data/")
data.is_parent_of(S3Path("my-bucket", "data", "2024", "report.csv"))
[68]:
True
is_prefix_of tests the key as a string, the same as the Prefix of the S3 list APIs. The file data is a prefix of data-2024.csv, but not its parent:
[69]:
S3Path("my-bucket", "data").is_prefix_of(S3Path("my-bucket", "data-2024.csv"))
[69]:
True
7. Compare, sort and hash¶
Two paths are equal when they have the same bucket, the same parts and the same type:
[70]:
S3Path("my-bucket", "a.txt") == S3Path("s3://my-bucket/a.txt")
[70]:
True
So a file and a folder of the same name are not equal:
[71]:
S3Path("my-bucket", "data") == S3Path("my-bucket", "data/")
[71]:
False
Paths are hashable, so they can be set members or dict keys:
[72]:
sizes = {}
sizes[S3Path("my-bucket", "a.txt")] = 100
sizes[S3Path("s3://my-bucket/a.txt")]
[72]:
100
sorted orders paths part by part, like pathlib: a folder comes right before its content.
[73]:
paths = [
S3Path("my-bucket", "a-b.txt"),
S3Path("my-bucket", "a", "b.txt"),
S3Path("my-bucket", "a/"),
]
for p in sorted(paths):
print(p)
S3Path('s3://my-bucket/a/')
S3Path('s3://my-bucket/a/b.txt')
S3Path('s3://my-bucket/a-b.txt')
This is not the order of the S3 list APIs, which sort keys as strings (- comes before /). Sort by key to get that order:
[74]:
def get_key(p):
return p.key
for p in sorted(paths, key=get_key):
print(p)
S3Path('s3://my-bucket/a-b.txt')
S3Path('s3://my-bucket/a/')
S3Path('s3://my-bucket/a/b.txt')
8. Serialize¶
to_dict gives the three fields that define a path (its type is S3PathDict, a TypedDict); the dict can be stored as JSON:
[75]:
p = S3Path("my-bucket", "folder", "file.txt")
data = p.to_dict()
data
[75]:
{'bucket': 'my-bucket', 'parts': ['folder', 'file.txt'], 'is_dir': False}
from_dict builds the path back:
[76]:
S3Path.from_dict(data) == p
[76]:
True
Pickle works too, and keeps the metadata loaded from S3:
[77]:
import pickle
pickle.loads(pickle.dumps(p)) == p
[77]:
True
Common pitfalls¶
Forgetting the trailing slash.
S3Path("my-bucket", "folder")is a file. Folder methods such asiter_objectsraiseS3PathIsNotFolderErroron it, and joining onto it is deprecated.Sorting and S3 order.
sorted(paths)is not the order S3 returns; see section 7.Attributes on a path.
S3Pathhas__slots__, sop.my_attr = 1raisesAttributeError. Keep your own data in adictkeyed by the path.
See also¶
Read and Write: the first chapter that calls AWS.