简体   繁体   中英

Move files from one bucket to a folder inside another bucket

我是 boto3 的新手,能够将文件从一个存储桶移动到另一个存储桶,但是,我需要将文件移动到另一个存储桶中的文件夹中

There is no 'move' command in Amazon S3. Instead, you will need to:

  • Use copy_object() to copy the object to a new Key (which includes the full path of the object)
  • Then delete_object() on the old object

The destination for the copy can be the same bucket or a different bucket.

Folders do not really exist, so you can copy an object to any path without first creating the folders.

If you don't need to use boto3, a simpler method is to use the AWS Command-Line Interface (CLI) :

aws s3 mv s3://bucket1/foo/object.txt s3://bucket2/bar/object.txt

You can even move whole 'folders':

aws s3 mv s3://bucket1/foo s3://bucket2/ --recursive

With boto3, it's pretty simple. As described in the docs :

import boto3
s3 = boto3.resource('s3')
copy_source = {
    'Bucket': 'mybucket',
    'Key': 'mykey'
}
s3.meta.client.copy(copy_source, 'otherbucket', 'otherkey')

And after you copy your file from one bucket to another one, you can delete it:

obj = s3.Object('bucket_name', 'key')
obj.delete()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM