我試圖列出存盤桶中的所有檔案。這是我的代碼
import boto3
s3 = boto3.resource('s3')
my_bucket = s3.Bucket('my_project')
for my_bucket_object in my_bucket.objects.all():
print(my_bucket_object.key)
有用。我得到所有檔案的名稱。但是,當我嘗試對檔案夾執行相同操作時,代碼會引發錯誤
import boto3
s3 = boto3.resource('s3')
my_bucket = s3.Bucket('my_project/data/') # add the folder name
for my_bucket_object in my_bucket.objects.all():
print(my_bucket_object.key)
這是錯誤:
botocore.exceptions.ParamValidationError: Parameter validation failed:
Invalid bucket name "carlos-cryptocurrency-research-project/data/": Bucket name must match the regex "^[a-zA-Z0-9.\-_]{1,255}$" or be an ARN matching the regex "^arn:(aws).*:(s3|s3-object-lambda):[a-z\-0-9]*:[0-9]{12}:accesspoint[/:][a-zA-Z0-9\-.]{1,63}$|^arn:(aws).*:s3-outposts:[a-z\-0-9] :[0-9]{12}:outpost[/:][a-zA-Z0-9\-]{1,63}[/:]accesspoint[/:][a-zA-Z0-9\-]{1,63}$"
我確定檔案夾名稱正確,我嘗試將其替換為 Amazon 資源名稱 (ARN) 和 S3 URI,但仍然出現錯誤。
uj5u.com熱心網友回復:
您不能在 Bucket 建構式中指定前綴/檔案夾。而是使用客戶端級 API 并呼叫list_objects_v2如下所示:
import boto3
client = boto3.client('s3')
response = client.list_objects_v2(
Bucket='my_bucket',
Prefix='data/')
for content in response.get('Contents', []):
print(content['Key'])
請注意,這將產生最多 1000 個 S3 物件。如果需要,您可以使用分頁器。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/437480.html
下一篇:在DynamoDBTransactWriteItemsConditionCheck與UpdateItem相同的專案中
