0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

boto3 で S3 オブジェクトを mv, rename

Last updated at Posted at 2023-09-26

別にどうということはないのだけど、あとで使いまわしそうなのでメモしておくやつ。

AWS CLI には aws s3 mv というコマンドがあるが、Amazon S3 そのものにはオブジェクトの Key の変更 (≒ 移動やリネーム) に相当する API が存在しないので、実際には CopyObject してから古い方を DeleteObject することになる。

Python で同様のことをしたい場合、boto3 の S3 Client には aws s3 mv 相当のメソッドは無いので、

def s3_move_object(s3, *, BucketFrom: str, BucketTo: str | None = None, KeyFrom: str, KeyTo: str):
    if BucketTo is None:
        BucketTo = BucketFrom
    s3.copy_object(Bucket=BucketTo, Key=KeyTo, CopySource={"Bucket": BucketFrom, "Key": KeyFrom})
    s3.delete_object(Bucket=BucketFrom, Key=KeyFrom)

こういう関数を作っておくと、

import boto3

s3 = boto3.client("s3")

s3_move_object(s3, BucketFrom="mybucket", KeyFrom="mydir/foo.txt", KeyTo="mydir/bar.txt")

こんなふうに使えて便利。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?