我正在嘗試將所有文??件從一個檔案夾復制到s3 存盤桶中的另一個檔案夾。我看到了很多從一個存盤桶移動到另一個存盤桶而不是從一個檔案夾移動到另一個檔案夾的示例。
從我在網上看到的示例中,我撰寫了以下代碼。
import boto3
s3_resource = boto3.resource('s3')
src = 'old_folder'
dest = 'new_folder'
for key in s3_resource.list_objects(Bucket=config.S3_BUCKET)['Contents']:
files = key['Key']
copy_source = {'Bucket': config.S3_BUCKET, 'Key': f'{src}/{files}'}
s3_resource.meta.client.copy(
copy_source, f'{config.S3_BUCKET}/{dest}/', f'{src}/{files}')
但是,當我運行代碼時,出現以下錯誤:
AttributeError: 's3.ServiceResource' object has no attribute 'list_objects'
對于以下行:for key in s3_resource.list_objects(Bucket=config.S3_BUCKET)['Contents']:
我相信我收到了錯誤,因為我正在使用boto3.resource(s3)而不是boto3.client(s3)我在網上看到的示例似乎用于boto3.resource(s3)將檔案從一個存盤桶移動到另一個存盤桶。
使用python將所有檔案從一個檔案夾移動到s3中同一存盤桶中的另一個檔案夾的正確方法是什么?
uj5u.com熱心網友回復:
我修改了代碼并添加了分頁。請看一下:
s3 = boto3.client('s3')
src = 'old_folder'
dest = 'new_folder'
paginator = s3.get_paginator('list_objects')
operation_parameters = {'Bucket': config.S3_BUCKET,
'Prefix': src}
page_iterator = paginator.paginate(**operation_parameters)
for page in page_iterator:
for obj in page['Contents']:
file = obj['Key']
#print(file)
dest_key = file.replace(src, dest)
#print("dest_key)
s3.copy_object(Bucket=config.S3_BUCKET,
CopySource=f'/{config.S3_BUCKET}/{file}',
Key=dest_key)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/472780.html
