{ "cells": [ { "cell_type": "markdown", "id": "a4cb29b4", "metadata": {}, "source": [ "# Path Manipulation\n", "\n", "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." ] }, { "cell_type": "code", "execution_count": 1, "id": "2281223c", "metadata": {}, "outputs": [], "source": [ "from s3pathlib.api import S3Path" ] }, { "cell_type": "markdown", "id": "7ff97125", "metadata": {}, "source": [ "## 1. Build a path\n", "\n", "`S3Path(bucket, *parts)`. The first argument is the bucket, the others are parts of the key:" ] }, { "cell_type": "code", "execution_count": 2, "id": "a700a04b", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "S3Path('s3://my-bucket/folder/file.txt')" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "S3Path(\"my-bucket\", \"folder\", \"file.txt\")" ] }, { "cell_type": "markdown", "id": "6ce68688", "metadata": {}, "source": [ "The first argument can also hold the whole path, as `bucket/key`, an S3 URI or an S3 ARN:" ] }, { "cell_type": "code", "execution_count": 3, "id": "726a4a21", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "S3Path('s3://my-bucket/folder/file.txt')" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "S3Path(\"my-bucket/folder/file.txt\")" ] }, { "cell_type": "code", "execution_count": 4, "id": "39409630", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "S3Path('s3://my-bucket/folder/file.txt')" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "S3Path(\"s3://my-bucket/folder/file.txt\")" ] }, { "cell_type": "code", "execution_count": 5, "id": "914efc34", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "S3Path('s3://my-bucket/folder/file.txt')" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "S3Path(\"arn:aws:s3:::my-bucket/folder/file.txt\")" ] }, { "cell_type": "markdown", "id": "b0c4b3ac", "metadata": {}, "source": [ "Repeated `/` are collapsed and empty parts are ignored:" ] }, { "cell_type": "code", "execution_count": 6, "id": "0d613b0d", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "S3Path('s3://my-bucket/folder/sub/file.txt')" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "S3Path(\"my-bucket\", \"folder//sub/\", \"\", \"file.txt\")" ] }, { "cell_type": "markdown", "id": "d44a8696", "metadata": {}, "source": [ "The **last non-empty part decides the type**: a trailing `/` makes a folder (a \"dir\"), otherwise it is a file." ] }, { "cell_type": "code", "execution_count": 7, "id": "379d284c", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "S3Path('s3://my-bucket/folder/data')" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "S3Path(\"my-bucket\", \"folder\", \"data\")" ] }, { "cell_type": "code", "execution_count": 8, "id": "284231ef", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "S3Path('s3://my-bucket/folder/data/')" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "S3Path(\"my-bucket\", \"folder\", \"data/\")" ] }, { "cell_type": "markdown", "id": "9e62cc95", "metadata": {}, "source": [ "`from_s3_uri` and `from_s3_arn` accept only that format, which is useful when the input comes from users:" ] }, { "cell_type": "code", "execution_count": 9, "id": "06e9f38d", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "S3Path('s3://my-bucket/folder/')" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "S3Path.from_s3_uri(\"s3://my-bucket/folder/\")" ] }, { "cell_type": "code", "execution_count": 10, "id": "a60dcdfc", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "S3Path('s3://my-bucket/folder/file.txt')" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "S3Path.from_s3_arn(\"arn:aws-cn:s3:::my-bucket/folder/file.txt\")" ] }, { "cell_type": "code", "execution_count": 11, "id": "d35df887", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "S3ValidationError: S3 URI must start with 's3://', got 'my-bucket/folder/'\n" ] } ], "source": [ "from s3pathlib.api import exc\n", "\n", "try:\n", " S3Path.from_s3_uri(\"my-bucket/folder/\")\n", "except exc.S3ValidationError as e:\n", " print(f\"{type(e).__name__}: {e}\")" ] }, { "cell_type": "markdown", "id": "800f1be8", "metadata": {}, "source": [ "The constructor rejects what is clearly not an S3 path, such as an HTTPS URL:" ] }, { "cell_type": "code", "execution_count": 12, "id": "0fe7e264", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "S3ValidationError: bucket 'https:' in 'https://my-bucket.s3.amazonaws.com/file.txt' contains ':', which is not allowed in any bucket name\n" ] } ], "source": [ "try:\n", " S3Path(\"https://my-bucket.s3.amazonaws.com/file.txt\")\n", "except exc.S3ValidationError as e:\n", " print(f\"{type(e).__name__}: {e}\")" ] }, { "cell_type": "markdown", "id": "7af355a5", "metadata": {}, "source": [ "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:" ] }, { "cell_type": "code", "execution_count": 13, "id": "8c1d3190", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "S3ValidationError: Bucket names can consist only of lowercase letters, numbers, dots (.), and hyphens (-). invalid char found ['B', 'M', '_']\n" ] } ], "source": [ "from s3pathlib.api import validate_s3_bucket\n", "\n", "try:\n", " validate_s3_bucket(\"My_Bucket\")\n", "except exc.S3ValidationError as e:\n", " print(f\"{type(e).__name__}: {e}\")" ] }, { "cell_type": "markdown", "id": "9ed9bbc0", "metadata": {}, "source": [ "`validate_s3_key`, `validate_s3_uri` and `validate_s3_arn` check the other parts the same way." ] }, { "cell_type": "markdown", "id": "6e2e1165", "metadata": {}, "source": [ "## 2. The six kinds of path\n", "\n", "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)." ] }, { "cell_type": "code", "execution_count": 14, "id": "d663f1b2", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "S3Path('s3://my-bucket/folder/file.txt')" ] }, "execution_count": 14, "metadata": {}, "output_type": "execute_result" } ], "source": [ "file = S3Path(\"my-bucket\", \"folder\", \"file.txt\")\n", "file" ] }, { "cell_type": "code", "execution_count": 15, "id": "1922f886", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "S3Path('s3://my-bucket/folder/')" ] }, "execution_count": 15, "metadata": {}, "output_type": "execute_result" } ], "source": [ "folder = S3Path(\"my-bucket\", \"folder/\")\n", "folder" ] }, { "cell_type": "code", "execution_count": 16, "id": "b4c36783", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "S3Path('s3://my-bucket/')" ] }, "execution_count": 16, "metadata": {}, "output_type": "execute_result" } ], "source": [ "bucket = S3Path(\"my-bucket\")\n", "bucket" ] }, { "cell_type": "markdown", "id": "0ab40a02", "metadata": {}, "source": [ "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:" ] }, { "cell_type": "code", "execution_count": 17, "id": "7100336e", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "S3RelPath('folder/file.txt')" ] }, "execution_count": 17, "metadata": {}, "output_type": "execute_result" } ], "source": [ "relpath_file = S3Path.make_relpath(\"folder\", \"file.txt\")\n", "relpath_file" ] }, { "cell_type": "code", "execution_count": 18, "id": "db922d9a", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "S3RelPath('folder/')" ] }, "execution_count": 18, "metadata": {}, "output_type": "execute_result" } ], "source": [ "relpath_dir = S3Path.make_relpath(\"folder/\")\n", "relpath_dir" ] }, { "cell_type": "code", "execution_count": 19, "id": "6eef5117", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "S3VoidPath()" ] }, "execution_count": 19, "metadata": {}, "output_type": "execute_result" } ], "source": [ "void = S3Path()\n", "void" ] }, { "cell_type": "markdown", "id": "6c028bf7", "metadata": {}, "source": [ "The `is_*` methods tell them apart. A bucket is also a dir:" ] }, { "cell_type": "code", "execution_count": 20, "id": "ecb57bc0", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "S3Path('s3://my-bucket/folder/file.txt') is_file: True is_dir: False is_bucket: False\n", "S3Path('s3://my-bucket/folder/') is_file: False is_dir: True is_bucket: False\n", "S3Path('s3://my-bucket/') is_file: False is_dir: True is_bucket: True\n", "S3RelPath('folder/file.txt') is_file: True is_dir: False is_bucket: False\n", "S3RelPath('folder/') is_file: False is_dir: True is_bucket: False\n", "S3VoidPath() is_file: False is_dir: False is_bucket: False\n" ] } ], "source": [ "paths = [file, folder, bucket, relpath_file, relpath_dir, void]\n", "for p in paths:\n", " print(p, \"is_file:\", p.is_file(), \"is_dir:\", p.is_dir(), \"is_bucket:\", p.is_bucket())" ] }, { "cell_type": "markdown", "id": "90ca0297", "metadata": {}, "source": [ "Void is also a relative path:" ] }, { "cell_type": "code", "execution_count": 21, "id": "785cad78", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "S3Path('s3://my-bucket/folder/file.txt') is_relpath: False is_void: False\n", "S3Path('s3://my-bucket/folder/') is_relpath: False is_void: False\n", "S3Path('s3://my-bucket/') is_relpath: False is_void: False\n", "S3RelPath('folder/file.txt') is_relpath: True is_void: False\n", "S3RelPath('folder/') is_relpath: True is_void: False\n", "S3VoidPath() is_relpath: True is_void: True\n" ] } ], "source": [ "for p in paths:\n", " print(p, \"is_relpath:\", p.is_relpath(), \"is_void:\", p.is_void())" ] }, { "cell_type": "markdown", "id": "9183ba5b", "metadata": {}, "source": [ "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." ] }, { "cell_type": "code", "execution_count": 22, "id": "73f142a8", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "S3Path('s3://my-bucket/folder/file.txt') bucket: 'my-bucket' key: 'folder/file.txt' uri: 's3://my-bucket/folder/file.txt'\n", "S3Path('s3://my-bucket/folder/') bucket: 'my-bucket' key: 'folder/' uri: 's3://my-bucket/folder/'\n", "S3Path('s3://my-bucket/') bucket: 'my-bucket' key: '' uri: 's3://my-bucket/'\n", "S3RelPath('folder/file.txt') bucket: None key: 'folder/file.txt' uri: None\n", "S3RelPath('folder/') bucket: None key: 'folder/' uri: None\n", "S3VoidPath() bucket: None key: '' uri: None\n" ] } ], "source": [ "for p in paths:\n", " print(p, \"bucket:\", repr(p.bucket), \"key:\", repr(p.key), \"uri:\", repr(p.uri))" ] }, { "cell_type": "markdown", "id": "be2a8860", "metadata": {}, "source": [ "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`:" ] }, { "cell_type": "code", "execution_count": 23, "id": "46249cc4", "metadata": {}, "outputs": [], "source": [ "file.ensure_file()" ] }, { "cell_type": "code", "execution_count": 24, "id": "234d5f37", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "S3PathIsNotFolderError: 's3://my-bucket/folder/file.txt' is not a dir!\n" ] } ], "source": [ "try:\n", " file.ensure_dir()\n", "except exc.S3PathIsNotFolderError as e:\n", " print(f\"{type(e).__name__}: {e}\")" ] }, { "cell_type": "markdown", "id": "38df46c9", "metadata": {}, "source": [ "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`." ] }, { "cell_type": "code", "execution_count": 25, "id": "dddb2d93", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "S3PathIsNotRelpathError: 's3://my-bucket/' is not a relpath!\n" ] } ], "source": [ "try:\n", " bucket.ensure_relpath()\n", "except TypeError as e:\n", " print(f\"{type(e).__name__}: {e}\")" ] }, { "cell_type": "markdown", "id": "f2eaadcd", "metadata": {}, "source": [ "## 3. Attributes\n", "\n", "The name parts follow `pathlib`: `basename` is `name`, `fname` is `stem`, `ext` is `suffix`." ] }, { "cell_type": "code", "execution_count": 26, "id": "a39af3bf", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "p.parts = ['data', '2024', 'report.tar.gz']\n" ] } ], "source": [ "p = S3Path(\"my-bucket\", \"data\", \"2024\", \"report.tar.gz\")\n", "print(f\"{p.parts = }\")" ] }, { "cell_type": "code", "execution_count": 27, "id": "eb57917b", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "p.basename = 'report.tar.gz'\n" ] } ], "source": [ "print(f\"{p.basename = }\")" ] }, { "cell_type": "code", "execution_count": 28, "id": "54699ab4", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "p.fname = 'report.tar'\n" ] } ], "source": [ "print(f\"{p.fname = }\")" ] }, { "cell_type": "code", "execution_count": 29, "id": "30804a68", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "p.ext = '.gz'\n" ] } ], "source": [ "print(f\"{p.ext = }\")" ] }, { "cell_type": "markdown", "id": "3c6f4783", "metadata": {}, "source": [ "`dirname` is the name of the parent folder:" ] }, { "cell_type": "code", "execution_count": 30, "id": "cafe876a", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "p.dirname = '2024'\n" ] } ], "source": [ "print(f\"{p.dirname = }\")" ] }, { "cell_type": "markdown", "id": "780dd0db", "metadata": {}, "source": [ "`abspath` and `dirpath` are the Unix style paths from the bucket, which works like a drive; `root` is the bucket." ] }, { "cell_type": "code", "execution_count": 31, "id": "a648a66f", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "p.abspath = '/data/2024/report.tar.gz'\n" ] } ], "source": [ "print(f\"{p.abspath = }\")" ] }, { "cell_type": "code", "execution_count": 32, "id": "873dce79", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "p.dirpath = '/data/2024/'\n" ] } ], "source": [ "print(f\"{p.dirpath = }\")" ] }, { "cell_type": "code", "execution_count": 33, "id": "4fef89b2", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "p.root = S3Path('s3://my-bucket/')\n" ] } ], "source": [ "print(f\"{p.root = }\")" ] }, { "cell_type": "markdown", "id": "2f0091c4", "metadata": {}, "source": [ "`parent` is always a dir:" ] }, { "cell_type": "code", "execution_count": 34, "id": "e1251986", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "S3Path('s3://my-bucket/data/2024/')" ] }, "execution_count": 34, "metadata": {}, "output_type": "execute_result" } ], "source": [ "p.parent" ] }, { "cell_type": "markdown", "id": "c0e0cb07", "metadata": {}, "source": [ "`parents` goes up to the bucket, like `pathlib.PurePath.parents`:" ] }, { "cell_type": "code", "execution_count": 35, "id": "e10a4a36", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "S3Path('s3://my-bucket/data/2024/')\n", "S3Path('s3://my-bucket/data/')\n", "S3Path('s3://my-bucket/')\n" ] } ], "source": [ "for parent in p.parents:\n", " print(parent)" ] }, { "cell_type": "markdown", "id": "1dfff118", "metadata": {}, "source": [ "For a relative path, `parents` ends with void:" ] }, { "cell_type": "code", "execution_count": 36, "id": "6818dbb5", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "S3RelPath('a/b/')\n", "S3RelPath('a/')\n", "S3VoidPath()\n" ] } ], "source": [ "for parent in S3Path.make_relpath(\"a/b/c.txt\").parents:\n", " print(parent)" ] }, { "cell_type": "markdown", "id": "0dda0ece", "metadata": {}, "source": [ "A folder's `basename` is the folder name:" ] }, { "cell_type": "code", "execution_count": 37, "id": "e2aadb82", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "folder.basename = '2024'\n" ] } ], "source": [ "folder = S3Path(\"my-bucket\", \"data\", \"2024/\")\n", "print(f\"{folder.basename = }\")" ] }, { "cell_type": "markdown", "id": "d4519856", "metadata": {}, "source": [ "A folder has no file name and no extension, so `fname` and `ext` raise:" ] }, { "cell_type": "code", "execution_count": 38, "id": "7743f8b6", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "S3PathIsNotFileError: 's3://my-bucket/data/2024/' is not a file, it has no ext!\n" ] } ], "source": [ "try:\n", " folder.ext\n", "except exc.S3PathIsNotFileError as e:\n", " print(f\"{type(e).__name__}: {e}\")" ] }, { "cell_type": "markdown", "id": "d97fa74a", "metadata": {}, "source": [ "`arn` and `console_url` use the commercial `aws` partition:" ] }, { "cell_type": "code", "execution_count": 39, "id": "96c380cc", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "p.arn = 'arn:aws:s3:::my-bucket/folder/file.txt'\n" ] } ], "source": [ "p = S3Path(\"my-bucket\", \"folder\", \"file.txt\")\n", "print(f\"{p.arn = }\")" ] }, { "cell_type": "code", "execution_count": 40, "id": "4ebd701a", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "p.console_url = 'https://console.aws.amazon.com/s3/object/my-bucket?prefix=folder/file.txt'\n" ] } ], "source": [ "print(f\"{p.console_url = }\")" ] }, { "cell_type": "markdown", "id": "05d8a534", "metadata": {}, "source": [ "`get_arn` and `get_console_url` take another partition (`aws-cn`, `aws-us-gov`, `aws-eusc`) or a region:" ] }, { "cell_type": "code", "execution_count": 41, "id": "45aaacdc", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'arn:aws-us-gov:s3:::my-bucket/folder/file.txt'" ] }, "execution_count": 41, "metadata": {}, "output_type": "execute_result" } ], "source": [ "p.get_arn(\"aws-us-gov\")" ] }, { "cell_type": "markdown", "id": "e15b40a2", "metadata": {}, "source": [ "`AwsPartitionEnum` has the partition names:" ] }, { "cell_type": "code", "execution_count": 42, "id": "6058a69a", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'arn:aws-cn:s3:::my-bucket/folder/file.txt'" ] }, "execution_count": 42, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from s3pathlib.api import AwsPartitionEnum\n", "\n", "p.get_arn(AwsPartitionEnum.aws_cn)" ] }, { "cell_type": "code", "execution_count": 43, "id": "a91cbf2e", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'https://us-west-2.console.aws.amazon.com/s3/object/my-bucket?region=us-west-2&prefix=folder/file.txt'" ] }, "execution_count": 43, "metadata": {}, "output_type": "execute_result" } ], "source": [ "p.get_console_url(region=\"us-west-2\")" ] }, { "cell_type": "code", "execution_count": 44, "id": "e5d10ca5", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'https://console.amazonaws.cn/s3/object/my-bucket?prefix=folder/file.txt'" ] }, "execution_count": 44, "metadata": {}, "output_type": "execute_result" } ], "source": [ "p.get_console_url(partition=\"aws-cn\")" ] }, { "cell_type": "markdown", "id": "6f9ca68d", "metadata": {}, "source": [ "## 4. Join\n", "\n", "`/` puts a part **under a dir**:" ] }, { "cell_type": "code", "execution_count": 45, "id": "c001cdb6", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "S3Path('s3://my-bucket/folder/file.txt')" ] }, "execution_count": 45, "metadata": {}, "output_type": "execute_result" } ], "source": [ "S3Path(\"my-bucket\") / \"folder/\" / \"file.txt\"" ] }, { "cell_type": "markdown", "id": "ba430f81", "metadata": {}, "source": [ "`joinpath` joins several parts at once:" ] }, { "cell_type": "code", "execution_count": 46, "id": "02cb826e", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "S3Path('s3://my-bucket/folder/file.txt')" ] }, "execution_count": 46, "metadata": {}, "output_type": "execute_result" } ], "source": [ "S3Path(\"my-bucket\").joinpath(\"folder\", \"file.txt\")" ] }, { "cell_type": "markdown", "id": "26dfd5ef", "metadata": {}, "source": [ "So does a list on the right side of `/`:" ] }, { "cell_type": "code", "execution_count": 47, "id": "a7e67487", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "S3Path('s3://my-bucket/folder/file.txt')" ] }, "execution_count": 47, "metadata": {}, "output_type": "execute_result" } ], "source": [ "S3Path(\"my-bucket\") / [\"folder\", \"file.txt\"]" ] }, { "cell_type": "markdown", "id": "011d74ca", "metadata": {}, "source": [ "A relative path can be joined too, which is how you rebuild a path under another folder:" ] }, { "cell_type": "code", "execution_count": 48, "id": "f68eabad", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "S3Path('s3://my-bucket/data/2024/report.csv')" ] }, "execution_count": 48, "metadata": {}, "output_type": "execute_result" } ], "source": [ "relpath = S3Path.make_relpath(\"2024/\", \"report.csv\")\n", "S3Path(\"my-bucket\", \"data/\") / relpath" ] }, { "cell_type": "markdown", "id": "f3f584a2", "metadata": {}, "source": [ "**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.\n", "\n", "The cell below catches the warning to show its message:" ] }, { "cell_type": "code", "execution_count": 49, "id": "490921ad", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "'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\")).\n" ] } ], "source": [ "import warnings\n", "\n", "with warnings.catch_warnings(record=True) as records:\n", " warnings.simplefilter(\"always\")\n", " S3Path(\"my-bucket\") / \"folder\" / \"file.txt\"\n", "\n", "print(records[0].message)" ] }, { "cell_type": "markdown", "id": "ab60d309", "metadata": {}, "source": [ "## 5. Change a path\n", "\n", "A path never changes; these methods return a new one. `change` replaces some attributes and keeps the others." ] }, { "cell_type": "code", "execution_count": 50, "id": "d4f85da0", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "S3Path('s3://other-bucket/data/2024/report.csv')" ] }, "execution_count": 50, "metadata": {}, "output_type": "execute_result" } ], "source": [ "p = S3Path(\"my-bucket\", \"data\", \"2024\", \"report.csv\")\n", "p.change(new_bucket=\"other-bucket\")" ] }, { "cell_type": "code", "execution_count": 51, "id": "ca5d74af", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "S3Path('s3://my-bucket/data/2024/report.json')" ] }, "execution_count": 51, "metadata": {}, "output_type": "execute_result" } ], "source": [ "p.change(new_ext=\".json\")" ] }, { "cell_type": "code", "execution_count": 52, "id": "cd4c7c2c", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "S3Path('s3://my-bucket/data/2024/summary.csv')" ] }, "execution_count": 52, "metadata": {}, "output_type": "execute_result" } ], "source": [ "p.change(new_fname=\"summary\")" ] }, { "cell_type": "code", "execution_count": 53, "id": "8d92fcd9", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "S3Path('s3://my-bucket/data/2024/2024-12.csv')" ] }, "execution_count": 53, "metadata": {}, "output_type": "execute_result" } ], "source": [ "p.change(new_basename=\"2024-12.csv\")" ] }, { "cell_type": "code", "execution_count": 54, "id": "d329b8c1", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "S3Path('s3://my-bucket/data/2025/report.csv')" ] }, "execution_count": 54, "metadata": {}, "output_type": "execute_result" } ], "source": [ "p.change(new_dirname=\"2025\")" ] }, { "cell_type": "code", "execution_count": 55, "id": "8f027f5c", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "S3Path('s3://my-bucket/archive/2024/report.csv')" ] }, "execution_count": 55, "metadata": {}, "output_type": "execute_result" } ], "source": [ "p.change(new_dirpath=\"archive/2024/\")" ] }, { "cell_type": "code", "execution_count": 56, "id": "cd61dad1", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "S3Path('s3://other-bucket/new/key.csv')" ] }, "execution_count": 56, "metadata": {}, "output_type": "execute_result" } ], "source": [ "p.change(new_bucket=\"other-bucket\", new_abspath=\"new/key.csv\")" ] }, { "cell_type": "markdown", "id": "c9cc3be4", "metadata": {}, "source": [ "`new_basename` can turn a file into a folder (end it with `/`):" ] }, { "cell_type": "code", "execution_count": 57, "id": "442ceb5c", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "S3Path('s3://my-bucket/data/2024/report/')" ] }, "execution_count": 57, "metadata": {}, "output_type": "execute_result" } ], "source": [ "p.change(new_basename=\"report/\")" ] }, { "cell_type": "markdown", "id": "9f4c21fd", "metadata": {}, "source": [ "Arguments that conflict or do not fit the path raise `ValueError`:" ] }, { "cell_type": "code", "execution_count": 58, "id": "c1d201a3", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "ValueError: new_ext has to be empty, or '.' followed by the extension, got 'json'\n" ] } ], "source": [ "try:\n", " p.change(new_ext=\"json\")\n", "except ValueError as e:\n", " print(f\"{type(e).__name__}: {e}\")" ] }, { "cell_type": "code", "execution_count": 59, "id": "cd1c47af", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "ValueError: pass new_dirpath or new_dirname, not both\n" ] } ], "source": [ "try:\n", " p.change(new_dirpath=\"a/\", new_dirname=\"b\")\n", "except ValueError as e:\n", " print(f\"{type(e).__name__}: {e}\")" ] }, { "cell_type": "markdown", "id": "17d6fe30", "metadata": {}, "source": [ "`to_dir` and `to_file` switch the type:" ] }, { "cell_type": "code", "execution_count": 60, "id": "e3d007a9", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "S3Path('s3://my-bucket/data/')" ] }, "execution_count": 60, "metadata": {}, "output_type": "execute_result" } ], "source": [ "S3Path(\"my-bucket\", \"data\").to_dir()" ] }, { "cell_type": "code", "execution_count": 61, "id": "7949973a", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "S3Path('s3://my-bucket/data')" ] }, "execution_count": 61, "metadata": {}, "output_type": "execute_result" } ], "source": [ "S3Path(\"my-bucket\", \"data/\").to_file()" ] }, { "cell_type": "markdown", "id": "d07f1b21", "metadata": {}, "source": [ "`copy` returns an equal path (without the metadata loaded from S3, see [Metadata and Tags](../05-Metadata-and-Tags/index.ipynb)):" ] }, { "cell_type": "code", "execution_count": 62, "id": "d3e7d0c5", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 62, "metadata": {}, "output_type": "execute_result" } ], "source": [ "p.copy() == p" ] }, { "cell_type": "markdown", "id": "b3b93791", "metadata": {}, "source": [ "## 6. Relative paths\n", "\n", "`relative_to` gives the path of `p` under a folder `base`:" ] }, { "cell_type": "code", "execution_count": 63, "id": "4e79fdf1", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "S3RelPath('2024/report.csv')" ] }, "execution_count": 63, "metadata": {}, "output_type": "execute_result" } ], "source": [ "base = S3Path(\"my-bucket\", \"data/\")\n", "p = S3Path(\"my-bucket\", \"data\", \"2024\", \"report.csv\")\n", "relpath = p.relative_to(base)\n", "relpath" ] }, { "cell_type": "markdown", "id": "0f64732a", "metadata": {}, "source": [ "It is the inverse of `/`: joining the relative path back onto `base` gives `p` again." ] }, { "cell_type": "code", "execution_count": 64, "id": "b05164b5", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 64, "metadata": {}, "output_type": "execute_result" } ], "source": [ "base / relpath == p" ] }, { "cell_type": "markdown", "id": "98066d93", "metadata": {}, "source": [ "This is how you mirror a folder somewhere else:" ] }, { "cell_type": "code", "execution_count": 65, "id": "3a43d8d2", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "S3Path('s3://other-bucket/backup/2024/report.csv')" ] }, "execution_count": 65, "metadata": {}, "output_type": "execute_result" } ], "source": [ "S3Path(\"other-bucket\", \"backup/\") / relpath" ] }, { "cell_type": "markdown", "id": "608908e1", "metadata": {}, "source": [ "`p - base` is a short way to write `p.relative_to(base)`:" ] }, { "cell_type": "code", "execution_count": 66, "id": "104ed0fe", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "S3RelPath('2024/report.csv')" ] }, "execution_count": 66, "metadata": {}, "output_type": "execute_result" } ], "source": [ "p - base" ] }, { "cell_type": "markdown", "id": "49f654ac", "metadata": {}, "source": [ "When `p` is not under `base`, there is no relative path, and it raises `ValueError`:" ] }, { "cell_type": "code", "execution_count": 67, "id": "539268fe", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "ValueError: 's3://my-bucket/data/2024/report.csv' is not under 's3://my-bucket/logs/'\n" ] } ], "source": [ "try:\n", " p.relative_to(S3Path(\"my-bucket\", \"logs/\"))\n", "except ValueError as e:\n", " print(f\"{type(e).__name__}: {e}\")" ] }, { "cell_type": "markdown", "id": "0d55127d", "metadata": {}, "source": [ "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.\n", "\n", "`is_parent_of` tests the folder hierarchy:" ] }, { "cell_type": "code", "execution_count": 68, "id": "6fb6904a", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 68, "metadata": {}, "output_type": "execute_result" } ], "source": [ "data = S3Path(\"my-bucket\", \"data/\")\n", "data.is_parent_of(S3Path(\"my-bucket\", \"data\", \"2024\", \"report.csv\"))" ] }, { "cell_type": "markdown", "id": "b46fd3ac", "metadata": {}, "source": [ "`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:" ] }, { "cell_type": "code", "execution_count": 69, "id": "73680781", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 69, "metadata": {}, "output_type": "execute_result" } ], "source": [ "S3Path(\"my-bucket\", \"data\").is_prefix_of(S3Path(\"my-bucket\", \"data-2024.csv\"))" ] }, { "cell_type": "markdown", "id": "ad1c1f5c", "metadata": {}, "source": [ "## 7. Compare, sort and hash\n", "\n", "Two paths are equal when they have the same bucket, the same parts and the same type:" ] }, { "cell_type": "code", "execution_count": 70, "id": "56ec843a", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 70, "metadata": {}, "output_type": "execute_result" } ], "source": [ "S3Path(\"my-bucket\", \"a.txt\") == S3Path(\"s3://my-bucket/a.txt\")" ] }, { "cell_type": "markdown", "id": "4674bdf0", "metadata": {}, "source": [ "So a file and a folder of the same name are not equal:" ] }, { "cell_type": "code", "execution_count": 71, "id": "85658b08", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 71, "metadata": {}, "output_type": "execute_result" } ], "source": [ "S3Path(\"my-bucket\", \"data\") == S3Path(\"my-bucket\", \"data/\")" ] }, { "cell_type": "markdown", "id": "7501cb86", "metadata": {}, "source": [ "Paths are hashable, so they can be `set` members or `dict` keys:" ] }, { "cell_type": "code", "execution_count": 72, "id": "386cceb5", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "100" ] }, "execution_count": 72, "metadata": {}, "output_type": "execute_result" } ], "source": [ "sizes = {}\n", "sizes[S3Path(\"my-bucket\", \"a.txt\")] = 100\n", "sizes[S3Path(\"s3://my-bucket/a.txt\")]" ] }, { "cell_type": "markdown", "id": "231338c1", "metadata": {}, "source": [ "`sorted` orders paths part by part, like `pathlib`: a folder comes right before its content." ] }, { "cell_type": "code", "execution_count": 73, "id": "84206726", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "S3Path('s3://my-bucket/a/')\n", "S3Path('s3://my-bucket/a/b.txt')\n", "S3Path('s3://my-bucket/a-b.txt')\n" ] } ], "source": [ "paths = [\n", " S3Path(\"my-bucket\", \"a-b.txt\"),\n", " S3Path(\"my-bucket\", \"a\", \"b.txt\"),\n", " S3Path(\"my-bucket\", \"a/\"),\n", "]\n", "for p in sorted(paths):\n", " print(p)" ] }, { "cell_type": "markdown", "id": "469e10d5", "metadata": {}, "source": [ "This is **not** the order of the S3 list APIs, which sort keys as strings (`-` comes before `/`). Sort by key to get that order:" ] }, { "cell_type": "code", "execution_count": 74, "id": "b2a0d3dd", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "S3Path('s3://my-bucket/a-b.txt')\n", "S3Path('s3://my-bucket/a/')\n", "S3Path('s3://my-bucket/a/b.txt')\n" ] } ], "source": [ "def get_key(p):\n", " return p.key\n", "\n", "\n", "for p in sorted(paths, key=get_key):\n", " print(p)" ] }, { "cell_type": "markdown", "id": "5b2fd795", "metadata": {}, "source": [ "## 8. Serialize\n", "\n", "`to_dict` gives the three fields that define a path (its type is `S3PathDict`, a `TypedDict`); the dict can be stored as JSON:" ] }, { "cell_type": "code", "execution_count": 75, "id": "d8f9def5", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'bucket': 'my-bucket', 'parts': ['folder', 'file.txt'], 'is_dir': False}" ] }, "execution_count": 75, "metadata": {}, "output_type": "execute_result" } ], "source": [ "p = S3Path(\"my-bucket\", \"folder\", \"file.txt\")\n", "data = p.to_dict()\n", "data" ] }, { "cell_type": "markdown", "id": "9b94f7e5", "metadata": {}, "source": [ "`from_dict` builds the path back:" ] }, { "cell_type": "code", "execution_count": 76, "id": "17bbc600", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 76, "metadata": {}, "output_type": "execute_result" } ], "source": [ "S3Path.from_dict(data) == p" ] }, { "cell_type": "markdown", "id": "57fc462d", "metadata": {}, "source": [ "Pickle works too, and keeps the metadata loaded from S3:" ] }, { "cell_type": "code", "execution_count": 77, "id": "8ee81f3d", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 77, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import pickle\n", "\n", "pickle.loads(pickle.dumps(p)) == p" ] }, { "cell_type": "markdown", "id": "4cdb9a6c", "metadata": {}, "source": [ "## Common pitfalls\n", "\n", "- **Forgetting the trailing slash.** `S3Path(\"my-bucket\", \"folder\")` is a file. Folder methods such as `iter_objects` raise `S3PathIsNotFolderError` on it, and joining onto it is deprecated.\n", "- **Sorting and S3 order.** `sorted(paths)` is not the order S3 returns; see section 7.\n", "- **Attributes on a path.** `S3Path` has `__slots__`, so `p.my_attr = 1` raises `AttributeError`. Keep your own data in a `dict` keyed by the path.\n", "\n", "## See also\n", "\n", "- [Quick Start](../01-Quick-Start/index.ipynb)\n", "- [Read and Write](../03-Read-and-Write/index.ipynb): the first chapter that calls AWS." ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.12.13" } }, "nbformat": 4, "nbformat_minor": 5 }